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.