Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is whereBetween in laravel inclusive?

In my database there are 4 students:

1st Student's created_at = 2016-05-12 02:23:51

2nd Student's created_at = 2016-05-27 07:37:45

3rd Student's created_at = 2016-05-29 07:40:29

4th Student's created_at = 2016-05-29 07:50:05

Why does my code only returns the 1st student?

$students = Student::select('id as ID_NO', 'fname as Firstname', 'lname as Lastname', 'created_at')
                             ->whereBetween('created_at', 
                              [Carbon::createFromDate(2016, 5, 12)->toDateString(),
                               Carbon::createFromDate(2016, 5, 27)->toDateString()])

The 1st and 2nd student should be returned. Is the "to" part inclusive in whereBetween or there's something wrong with my code ?

I need your help guys. Thanks in advance!

like image 335
Arth Limchiu Avatar asked Jun 02 '16 06:06

Arth Limchiu


3 Answers

For others who end up here and want the answer to the question asked (in case it's updated… "Is whereBetween in Laravel inclusive?"):

Yes.

like image 156
Curtis Blackwell Avatar answered Oct 23 '22 00:10

Curtis Blackwell


Laravel search between, this means it will get all the rows between 2016-05-12 00:00:00 and 2016-05-27 00:00:00. Your second user is created at 2016-05-27 07:37:45, this is outside the range so Laravel won't fetch it.

Use this and try if this works:

$students = Student::select('id as ID_NO', 'fname as Firstname', 'lname as Lastname', 'created_at')
    ->whereBetween('created_at' [
        Carbon::createFromDate(2016, 5, 12)->toDateString(),
        Carbon::createFromDate(2016, 5, 28)->toDateString()
    ])

Hope this works!

like image 34
Robin Dirksen Avatar answered Oct 22 '22 23:10

Robin Dirksen


You need to format your created_at to Y-m-d format. Please see the change:

$students = Student::select('id as ID_NO', 'fname as Firstname', 'lname as Lastname', 'created_at')
                                 ->whereBetween(DB::raw('date(created_at)'), 
                                  [Carbon::createFromDate(2016, 5, 12)->toDateString(),
                                   Carbon::createFromDate(2016, 5, 27)->toDateString()])
like image 36
Ali Avatar answered Oct 22 '22 23:10

Ali