In this blog post we will learn to get today records in laravel. we will use carbon and whereDate
method of laravel eloquent to fetch the today records. In laravel models save the data in column created_at
and created_at column stores the date time but if we want to fetch the records for today then it means we need to remove the time from created_at field so to do that we will use laravel eloquent whereDate method.
whereDate
method parse the date time to date then we use Carbon::today()
to get the date of today.
Table of Contents
Understand Get Today Records in Laravel with Example
To begin, let’s create a model. Open your terminal and run the following command
php artisan make:model Article
This command generates a new model named Record
in the app
directory.
Method 1: Using Eloquent’s whereDate
Method
Laravel’s Eloquent provides a convenient whereDate
method to filter records based on a specific date. To get today’s records, you can use this method in the controller or wherever you handle your data retrieval logic.
use App\Models\Article;
use Carbon\Carbon;
public function getTodayRecords()
{
$todayRecords = Article::whereDate('created_at', Carbon::today())->get();
// Process $todayRecords as needed
}
In this example, we’re querying the Article
model, filtering records where the created_at
date is equal to today’s date.
Method 2: Leveraging Raw SQL Queries
For scenarios where you prefer raw SQL queries, Laravel allows you to execute them seamlessly. Here’s an example:
use Illuminate\Support\Facades\DB;
public function getTodayRecords()
{
$todayRecords = DB::select("SELECT * FROM articles WHERE DATE(created_at) = CURDATE()");
// Process $todayRecords as needed
}
This method uses the DB::select
method to execute a raw SQL query that retrieves records where the date matches the current date.
Method 3: Customizing with Scope Methods
To enhance code readability and reusability, consider implementing a scope method in your Eloquent model.
// In the Record model
public function scopeTodayArticles($query)
{
return $query->whereDate('created_at', Carbon::today());
}
Now, you can effortlessly fetch today’s records in your controller:
$todayArticles = Article::scopeTodayArticles()->get();
Conclusion
In this guide, we explored multiple ways to get today records in Laravel. Whether you prefer Eloquent’s built-in methods, raw SQL queries, or custom scope methods, Laravel provides the flexibility to suit your coding style. Incorporate these techniques into your projects to streamline the process of fetching records based on the current date.
Remember, the key is understanding your project’s requirements and choosing the method that aligns best with your development workflow. Now, armed with this knowledge, you can efficiently retrieve today’s records in Laravel for a smoother and more productive coding experience.