![]() |
VOOZH | about |
In Laravel, filtering a collection involves selecting specific items based on set conditions, offering flexibility and control over data. This process helps refine collections to meet specific criteria for enhanced data management.
Below are the methods to filter a collection in Laravel:
Table of Content
The filter method in Laravel allows us to filter a collection using a callback function. This callback function receives each item in the collection as its argument and should return true if the item should be included in the filtered result or false otherwise.
Example: This example shows the filter method with a callback function.
Output:
👁 Screenshot-2024-04-27-153459
The reduce method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration. the reduce method iterates through each item in the collection. If an item is even, add it to the $carry array, acting as an accumulator.
Example: This example shows the filter a collection with using the reduce method.
Output:
👁 Screenshot-2024-04-27-153459
The reject method filters the collection using the given callback function . The function should return true if the item should be removed from the resulting collection. In our case we want to keep the even numbers in the collections and remove the odd numbers, so we will use the reject() method to remove the odd numbers from the collection.
Example: This example shows the filter a collection with using the reject() method.
Output: