Ever wanted to fetch records within a range of values? Let’s say you have a post table and a views column, and you just want to collect/retrieve rows with views within the range of 300-1000.
In this shot, I will teach you how to do that using the whereBetween()
method.
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.
$users = DB::table('users')
->whereBetween('votes', [1, 100])
->get();
The whereBetween()
method receives two parameters:
Let’s look at the syntax, we notice that the whereBetween()
method was chained to the table()
which is then called on the Db
facade.
From the example below we fetch users with ids between 1 to 100.
public function index()
{
$users = User::whereBetween('id', [1, 100])
->get();
return $users;
}
The output would be an array that can be looped through to fetch the individual user.