Get Database Search Results Between Two Date Time Period
In my database, there is a table called vehicle_schedule, and all the vehicle schedules are stored there. In that table, there is two columns name as date_from
date_to
.Both columns type is datetime
.When I pass date like 2019-03-20 09:00:00
2019-03-25 12:00:00
I need to get all the vehicle schedules between that two DateTime range.
So far I have tried this,
$vehicleSchedule=DB::table('vehicle_schedule')
->select('vehicle_schedule.*')
->whereRaw("date_from >=? AND date_to <=?",array($date_from,$date_to))
->get();
return response()->json(["vehicleSchedule"=>$vehicleSchedule,"message"=>"Vehicle Schedule got successfully"]);
I expect all the vehicle schedules are in that given range. But it only got vehicle schedules between date values only. When I check with the time constraint it does not working properly.
Answer
I highly recommend to use PHP Carbon
to work with any datetime
or timestamp
field.
To convert the datetime field to Carbon use this in model.
protected $dates = ['date_from','date_to'];
Then, convert the input time to Carbon inside controller
$date_from = Carbon::parse('2019-03-20 09:00:00');
$date_to = Carbon::parse('2019-03-25 12:00:00');
In this way the query will more shorter, cleaner and efficient.
$vehicleSchedule = DB::table('vehicle_schedule')
->where('date_from','>=',$date_from)
->where('date_to','<=',$date_to)
->get();
Related Questions
- → I can't do a foreign key, constraint error
- → How to implement DbDongle::convertTimestamps as workaround of invalid timestamps with MySql strict
- → MySQL error "Foreign key constraint is incorrectly formed"
- → Eloquent Multitable query
- → "Laravel 5.1" add user and project with userId
- → Database backup with custom code in laravel 5 and get the data upto 10 rows from per table in database
- → Laravel 5.1 QueryException when trying to delete a project
- → Using Array in '->where()' for Laravel Query Building
- → Chaining "Count of Columns" of a Method to Single Query Builder
- → Laravel Eloquent Joining Strange query
- → convert time using mysql laravel 5
- → How to update a column after an expiration date in MySQL?
- → Foreign key constraint fails on existing key