How to fetch Today’s Date Record in Laravel?

We can use the now() method from the carbon class where the clause can fetch today’s record in Laravel.

To begin with, let’s create a controller in which we will be fetching today’s date record from the database through the query builder. To create a controller run the below command in the terminal,

php artisan make:controller UserController

After creating the controller two classes need to be imported into it. First is the user model class and second is the carbon class that provides a now() method to get the current date. So let’s import both classes into UserController.php

use App\Models\User;
use Carbon\Carbon;

Next, create a todayRecords method into UserController class in which we will be fetching today’s records.

public function todayRecords()
{   
    $todayRecords = User::whereDate('created_at', Carbon::now())->get();
    $convertToArray = $todayRecords->toArray();
    dd($convertToArray);
}

The above method has a query that fetches today’s record through the whereDate() method that adds the date() function in the where clause. In whereDate() function two values are passed as in which first is column name and second is now() method that returns current date. After fetching the records, the toArray() function converts the collection into an array. We have two rows in the users table at the time of writing this article, so the above method returns the following response

array:2 [
  0 => array:6 [
    "id" => 5
    "name" => "john smith"
    "email" => "johnsmith@gmail.com"
    "email_verified_at" => "2022-10-26T10:58:35.000000Z"
    "created_at" => "2022-10-26T10:58:42.000000Z"
    "updated_at" => "2022-10-26T10:58:45.000000Z"
  ]
  1 => array:6 [
    "id" => 6
    "name" => "abott"
    "email" => "abott@gmail.com"
    "email_verified_at" => null
    "created_at" => "2022-10-26T11:06:52.000000Z"
    "updated_at" => "2022-10-26T11:06:54.000000Z"
  ]
]

Conclusion

This article demonstrates how to fetch today’s date records from a database in the Laravel framework. To fetch today’s record you need to use the whereDate() function in your query along with the now() method from the carbon class.