This article will give you example of laravel collection filter by value. Step by step explain laravel collection filter by key. Here you will learn laravel collection filter null. you can see laravel collection filter function. You just need to some step to done laravel collection filter empty.
Laravel Collection object provide several methods that will help to write your own logic. here we will learn how to use filter method of laravel collection.
In this example i will give you two example one with multidimensional array collection object with filter pass student. Another example we be simple example that will help you to remove null, empty, empty array value from collection object.
You can use collection filter like as bellow syntax:
filter()
filter(function( 'You can write logic here' ))
Now we will see both examples bellow:
Example 1:
public function index()
{
$myStudents = [
['id'=>1, 'name'=>'Hardik', 'mark' => 80],
['id'=>2, 'name'=>'Paresh', 'mark' => 20],
['id'=>3, 'name'=>'Akash', 'mark' => 34],
['id'=>4, 'name'=>'Sagar', 'mark' => 45],
];
$myStudents = collect($myStudents);
$passedstudents = $myStudents->filter(function ($value, $key) {
return data_get($value, 'mark') > 34;
});
$passedstudents = $passedstudents->all();
dd($passedstudents);
}
Output:
array:2 [▼
0 => array:3 [▼
"id" => 1
"name" => "Hardik"
"mark" => 80
]
3 => array:3 [▼
"id" => 4
"name" => "Sagar"
"mark" => 45
]
]
Example 2:
public function index()
{
$myArray = collect([2, 3, 5, null, false, '', 0, []]);
$myfilterArray = $myArray->filter()->all();
dd($myfilterArray);
}
Output:
array:3 [▼
0 => 2
1 => 3
2 => 5
]
I hope it can help you...
Do you like below Tutorials ?
- PHP Laravel 5.5 - import export data into excel and csv using maatwebsite
- Laravel 7.x and 6.x create custom facade example from scratch
- Node JS - Get Real time online users counter using socket io example
- PHP Laravel 7.x and 6.x - Bootstrap Admin Theme Integration example from scratch
- MySQL Query - How to select records of today to next Sunday ?
- Laravel 7.x and 6.x - username custom validation example
- Laravel 5.5 - Import Extract zip file using chumper/zipper package
- PHP Laravel Set Custom Validation Error Messages Example