2 ways to get records between two values in laravel

Laravel 1 min read

Table of Content

    Introduction

    Sometimes we need to filter data between two values [e.g. date] and we don't know how. Laravel makes this easy for us. So, today we will learn how to get records between two dates with a simple and easy way.

    Requisite

    Basic Understanding on laravel framework

    Using whereBetween() Method

    The whereBetween method filters the collection by determining if a specified item value is within a given range:

    $collection = collect([
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Chair', 'price' => 80],
        ['product' => 'Bookcase', 'price' => 150],
        ['product' => 'Pencil', 'price' => 30],
        ['product' => 'Door', 'price' => 100],
    ]);
    
    $filtered = $collection->whereBetween('price', [100, 200]);
    
    $filtered->all();
    
    /*
        [
            ['product' => 'Desk', 'price' => 200],
            ['product' => 'Bookcase', 'price' => 150],
            ['product' => 'Door', 'price' => 100],
        ]
    */
    

    Note: If you want to opposite of whereBetween or in another meaning: exclude the date between two dates use ``whereNotBetween` with the same steps as above code.

    Using where() Method

    The where method filters the collection by a given key / value pair:

    $collection = collect([
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Bookcase', 'price' => 150],
        ['product' => 'Door', 'price' => 100],
    ]);
    
    $filtered = $collection->where('price', '>=', 100)
                            ->where('price', '<=', 150);
    
    $filtered->all();
    
    /*
        [
            ['product' => 'Chair', 'price' => 100],
            ['product' => 'Bookcase', 'price' => 150],
            ['product' => 'Door', 'price' => 100],
        ]
    */
    

    Conclusion

    Today we knew how to get_records_between_two_values in Laravel using whereBetween and where methods

    Hope this quick article helps you and if you find something useful don't forget to follow me on Twitter for latest tips and tricks about laravel and the web development on general.


    Related Tags

    About the Author

    Oussama's Profile Picture
    Oussama
    Full Stack Web Developer

    I'm a full stack web developer and telecommunications engineer who love to share knowledge and build stuff online!


    Comments

    Join Our Newsletter

    Subscribe to Our Newsletter and never miss our offers, latest news, Articles, etc.

    Our news letter sent once a week, every tuesday.