How to Collection filter() Method in Laravel 8?

Jan 27, 2022 . Admin



Hi Dev,

I am going to explain you example of filter() method in laravel 8 collections , You will learn contains a very classified information about the basic concept of Laravel 8 Collection filter(). We will see the concept of filter item into laravel collection. We will filter data into single dimensional array, multi dimensional array.

We will use Illuminate\Support\Collection class provides a fluent. convenient wrapper for working with arrays of data. For example, check out the following code. We’ll use the collect helper to create a new collection instance from the array.

Let's see bellow example:

Step : 1 - Installation of Laravel Application

Use this command then download laravel project setup :

composer create-project --prefer-dist laravel/laravel blog

Collection – filter() Method

We will see how to use filter() into collection.

Suppose we have CollectionController.php a controller file inside /app/Http/Controllers folder.

Laravel Collection filter() with multi dimensional array.

Step : 2 - Create Controller
php artisan make:controller CollectionController
app/Http/Controllers/CollectionController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CollectionController extends Controller
{
    public function index()
    {
        $students = collect([
            ["id" => 1, "name" => "Piyush", "email" => "piyushkamani@gmail.com", "marks" => 88],
            ["id" => 2, "name" => "Pratik", "email" => "pratik@gmail.com", "marks" => 70],
            ["id" => 3, "name" => "Nikhil", "email" => "nikhil@gmail.com", "marks" => 75]
        ]);

        $passed = $students->filter(function ($value, $key) {
            return data_get($value, 'marks') > 70;
        });

        $passed = $passed->all();

        dd($passed);
    }
}
Output:
array:[
    0=>array:4[
        "id"=>1
        "name"=>"Piyush"
        "name"=>"piyushkamani@gmail.com"
        "mark"=>88
    ]
    1=>array:4[
        "id"=>3
        "name"=>"Nikhil"
        "name"=>"nikhil@gmail.com"
        "mark"=>75
    ]
]

I hope it will help you...

#Laravel 8