Laravel whereBetween, whereNotBetween eloquent query example

Laravel whereBetween, whereNotBetween eloquent query example

In this article lets understand Laravel whereBetween, whereNotBetween eloquent query with example. We will also look at the  whereBetweenColumns, whereNotBetweenColumns here.

1.  whereBetween query

Laravel syntax :

$users = User::whereBetween('rating', [1,4])->get();

Plain syntax: select * from `users` where `rating` between 1 and 4;

The whereBetween method verifies that a column’s value is between two values. Here we are fetching user rating between 1 to 4.

Result :

Laravel eloquent whereBetween  query

2.  whereNotBetween query

Laravel syntax :

$users = User::whereNotBetween('rating', [1,3])->get();

Plain syntax: select * from `users` where `rating` not between 1 and 3;

whereNotBetween does the reverse of what we did in first query. It will exclude the results of passed array and returns the rest of records.

Result :

Laravel whereNotBetween query

3.  whereBetweenColumns query

Laravel syntax :

$users = User::whereBetweenColumns('rating', ['min_rating','max_rating'])->get();

Plain syntax: select * from `users` where `rating` between `min_rating` and `max_rating`;

The whereBetweenColumns method verifies that a column’s value is between the two values of two columns in the same table row.

Result :

Laravel whereBetweenColumns query

4.  whereNotBetweenColumns query

Laravel syntax :

$users = User::whereNotBetweenColumns('rating', ['min_rating','max_rating'])->get();

Plain syntax: select * from `users` where `rating` not between `min_rating` and `max_rating`;

The whereNotBetweenColumns method verifies that a column’s value lies outside the two values of two columns in the same table row.

Result :

Laravel eloquent whereNotBetweenColumns query

That’s all on Laravel whereBetween, whereNotBetween eloquent query example. Also whereBetweenColumns, whereNotBetweenColumns. Hope this finds you helpful.

See other articles on Laravel here.