Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
communitycreator

How to use the wherebetween() method in Laravel

Chinweuba Elijah Azubuike

Overview

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.

Definition

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.

Syntax

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

Parameters

The whereBetween() method receives two parameters:

  1. Column name of the table.
  2. An array of two numbers.

Code

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.

Example

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

The output would be an array that can be looped through to fetch the individual user.

RELATED TAGS

laravel
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring