Laravel Eloquent how to use between operator

107,877

Solution 1

$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

Solution 2

The whereBetween method verifies that a column's value is between two values:

$users = DB::table('users')->whereBetween('votes', [1, 100])->get();

The whereNotBetween method verifies that a column's value lies outside of two values:

$users = DB::table('users')->whereNotBetween('votes', [1, 100])->get();

Laravel

Share:
107,877
GRowing
Author by

GRowing

Every time I find help in your answers I am endlessly thankful. I hope to give back with my insights and code as much as I receive.

Updated on December 14, 2021

Comments

  • GRowing
    GRowing over 2 years

    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?