Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent how to use between operator

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?

like image 815
GRowing Avatar asked Nov 04 '14 23:11

GRowing


People also ask

How can we get data between two dates using query in Laravel?

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.

How do I use whereBetween in Laravel?

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.


1 Answers

$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

like image 81
jsphpl Avatar answered Sep 25 '22 10:09

jsphpl