I am trying to find an elegant way in Eloquent and Laravel to say
select * from UserTable where Age between X and Y
Is there a between operator in Eloquent (I can't find it).
The closest i have gotten so far is chainging my query like this
$query->where(age, '>=', $ageFrom) ->where(age, '<=', $ageTo);
I also came across whereRaw that seems to work
$query->whereRaw('age BETWEEN ' . $ageFrom . ' AND ' . $ageTo . '');
Is there an actual Eloquent way (not raw) that deals with ranges?
Try to do something like this: $date1 = Carbon::today()->toDateString(); $date2 = Carbon::today()->toDateString(); $myModel = MyModel::find(1); $myModel->whereBetween('created_at', [$date1, $date2]); $myModel->get(); Of course, you will need to change the dates.
The whereBetween() method is a query builder chained alongside other Laravel query builders used to fetch data from the database. The whereBetween() method queries the database table to fetch rows of records from the database within a range of values.
$query->whereBetween('age', [$ageFrom, $ageTo]);
Look here: http://laravel.com/docs/4.2/queries#selects
Still holds true for Laravel 5: https://laravel.com/docs/5.8/queries#where-clauses
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With