Laravel Eloquent how to use between operator

PhpSqlLaravelLaravel 4Eloquent

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

$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 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGRowingView Question on Stackoverflow
Solution 1 - PhpjsphplView Answer on Stackoverflow
Solution 2 - PhpAli RazaView Answer on Stackoverflow