A.B.Developer A.B.Developer - 3 months ago 14
PHP Question

select records that x days left to their DATETIME formatted field in laravel

I have a

Test
Model that has these fields :

test_id
title
desc
start_date
end_date


start_date
and
end_date
fields have DATETIME format.

Now I want to select all records that 10 (for example) days (or less) left to their
start_date
,and
end_date
has not come.

I think that I should to use Carbon PHP API extension but I do not know How.

Answer

Setting your date mutator

First of all set your start_date as an instance of Carbon in your Test model. This will allow you easy manipulation of the datetime object it stores and interaction trough the Laravel query builder.

Building the query

$date = Carbon::now()->modify('+10 days')->toDateString();
$today = Carbon::now()->toDateString();
$results = Test::where('start_date', '<=', $date)
           ->andWhere('start_date', '>=', $today)
           ->get();

$results should contain Test models with your specified information.