Laravel

How to get current date record in Laravel

Laravel

How to get current date record in Laravel

In this tutorial we will learn how to get current Date records in Laravel 10. Working with date and time in PHP can be complicated. We have to deal with strtotime, formatting issues, lots of calculations, and more. the Carbon package can help make dealing with date and time in PHP much easier and more semantic

In order to use Carbon, you’ll need to import Carbon from the Carbon namespace. Luckily for us, Carbon is already included in Laravel.

Whenever we need to use Carbon, we can import like this:

<?php
use Carbon\Carbon;

If you want to fetch the current date records from database tables in laravel. Use the below Laravel eloquent Query for fetching the current date records.

<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        
        $users = User::whereDate('created_at', Carbon::today())->get(['name','created_at'])->toArray(); // get current date user data

        echo "<pre>";
        print_r($users);
        die;
    }

The output of the above laravel eloquent query looks like:

Array
(
    [0] => Array
        (
            [name] => Morton Fahey
            [created_at] => 2023-07-06T04:06:36.000000Z
        )

    [1] => Array
        (
            [name] => Ms. Kayla Murphy II
            [created_at] => 2023-07-06T04:06:36.000000Z
        )

    [2] => Array
        (
            [name] => Payton Cruickshank
            [created_at] => 2023-07-06T04:06:36.000000Z
        )
)

Thank You!