Laravel Collections Filter Method Example

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Today now in this blog,I will show you a example of how to use collection filter method in laravel application. From here you can know about easy way to use the filter method in laravel.

So the filter function takes a callback as an argument and also run filter over each item. Now if the test fails for a particular item, then it will also remove it from the collection.

Now the Illuminate\Support\Collection class provides a fluent, convenient wrapper for also working with arrays of data. Now here we’ll use the collect helper to create a new collection instance from the array.

Example 1:

/**
* The attributes that are mass assignable.
*
* @var array
*/
public function index()
{
    $collection = collect([1, 2, 3, null, false, '', 0, [], 5, 6]);

	$results = $collection->filter()->all();

    dd($results);
}

Output :

array:5 [?
  0 => 1
  1 => 2
  2 => 3
  8 => 5
  9 => 6
]

Example 2:

/**
* The attributes that are mass assignable.
*
* @var array
*/
public function index()
{
    $collection = collect([
                    ['name' => 'Ravi', 'age' => null],
                    ['name' => 'Jaydev', 'age' => 14],
                    ['name' => 'Sunil', 'age' => 23],
                    ['name' => 'Hardik', 'age' => 84],
                ]);

    $filtered = $collection->filter(function ($item) {
                    return data_get($item, 'age') >= 14;
                });

    $results = $filtered->all();

    dd($results);
}

Output :

array:3 [?
  1 => array:2 [?
    "name" => "Jaydev"
    "age" => 14
  ]
  2 => array:2 [?
    "name" => "Sunil"
    "age" => 23
  ]
  3 => array:2 [?
    "name" => "Hardik"
    "age" => 84
  ]
]

Read Also : How to Remove Special Character From String in PHP

I hope it will help you. Also you can follow us on Facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →