⌘K
Noting Found

View all related articles

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:

    1$collection = collect([
    2 ['product' => 'Desk', 'price' => 200],
    3 ['product' => 'Chair', 'price' => 80],
    4 ['product' => 'Bookcase', 'price' => 150],
    5 ['product' => 'Pencil', 'price' => 30],
    6 ['product' => 'Door', 'price' => 100],
    7]);
    8 
    9$filtered = $collection->whereBetween('price', [100, 200]);
    10 
    11$filtered->all();
    12 
    13/*
    14 [
    15 ['product' => 'Desk', 'price' => 200],
    16 ['product' => 'Bookcase', 'price' => 150],
    17 ['product' => 'Door', 'price' => 100],
    18 ]
    19*/

    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:

    1$collection = collect([
    2 ['product' => 'Desk', 'price' => 200],
    3 ['product' => 'Chair', 'price' => 100],
    4 ['product' => 'Bookcase', 'price' => 150],
    5 ['product' => 'Door', 'price' => 100],
    6]);
    7 
    8$filtered = $collection->where('price', '>=', 100)
    9 ->where('price', '<=', 150);
    10 
    11$filtered->all();
    12 
    13/*
    14 [
    15 ['product' => 'Chair', 'price' => 100],
    16 ['product' => 'Bookcase', 'price' => 150],
    17 ['product' => 'Door', 'price' => 100],
    18 ]
    19*/

    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 | Technical Writer

    Oussama is an experienced full-stack web developer with a strong focus on Laravel. He's passionate about crafting web applications with Filament and the TALL Stack. With 8+ years of experience, and he's a dedicated open-source contributor.

    Comments

    Join our newsletter

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

    We care about the protection of your data. Read our Privacy Policy.