How to compare dates using eloquent in laravel?

Member

by domenico , in category: PHP Frameworks , 5 months ago

How to compare dates using eloquent in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 5 months ago

@domenico 

To compare dates using Eloquent in Laravel, you can use the following methods provided by Carbon, the date and time library that Laravel utilizes:


isPast(): Checks if the date is in the past.


isFuture(): Checks if the date is in the future.


isToday(): Checks if the date is today.


isYesterday(): Checks if the date is yesterday.


isTomorrow(): Checks if the date is tomorrow.


equalTo($date): Checks if the date is equal to the given $date.


greaterThan($date): Checks if the date is greater than the given $date.


greaterThanOrEqualTo($date): Checks if the date is greater than or equal to the given $date.


lessThan($date): Checks if the date is less than the given $date.


lessThanOrEqualTo($date): Checks if the date is less than or equal to the given $date.


Here's an example of comparing dates using Eloquent in Laravel:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use IlluminateDatabaseEloquentModel;
use CarbonCarbon;

class YourModel extends Model
{
    // Your model's properties and methods ...

    public function scopeExpired($query)
    {
        return $query->where('expiration_date', '<', Carbon::now());
    }

    public function scopeUpcoming($query)
    {
        return $query->where('effective_date', '>', Carbon::now());
    }
}


In this example, we define two query scopes: scopeExpired() and scopeUpcoming(). The scopeExpired() scope checks if the "expiration_date" column is less than the current date and time, and the scopeUpcoming() scope checks if the "effective_date" column is greater than the current date and time.


You can then use these scopes in your queries like this:

1
2
3
$expiredItems = YourModel::expired()->get();

$upcomingItems = YourModel::upcoming()->get();


These queries will retrieve the records that have expired or are upcoming based on the dates stored in the corresponding columns.


Remember to include the Carbon namespace at the top of your file when using Carbon methods.

1
use CarbonCarbon;