How to Get records created today only using laravel

Hello Geeks ,In Laravel you can get records created today using the built-in query builder. Here’s a step-by-step guide to retrieve only the records created today.

  1. First, define a variable to store the current date:
$today = Carbon::today();

2. Then, use the ‘whereDatemethod in your query to retrieve only the records created today:

$records = DB::table('table_name')->whereDate('created_at', $today)->get();

3. If you want to retrieve records created today in a specific timezone, you can set it using the ‘timezonemethod:

$today = Carbon::today()->timezone('Asia/Jakarta');

4. Additionally, you can also retrieve records created today in a specific column. For example, if you want to retrieve records from a ‘created_atcolumn:

$records = DB::table('table_name')->whereDate('created_at', '=', $today)->get();

That’s it! You now have a list of all records created today using Laravel’s query builder.

Note: In the above example, ‘table_nameshould be replaced with the actual name of your table. Also, make sure to use the ‘usestatement at the top of your file to include the required namespaces:

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

Additionally, you can also use Laravel’s Eloquent ORM to retrieve records created today. The syntax is similar to the query builder, but with a few differences:

$records = ModelName::whereDate('created_at', $today)->get();

Where ‘ModelNameis the name of your Eloquent model.

I hope this helps you retrieve records created today in Laravel.

All the best nerd!

Leave a Reply