Laravel 10 Collection filter() Method Tutorial
Hi Friends,
I am going to explain to you an example of the filter() method in Laravel 10 collections, You will learn contains very classified information about the basic concept of Laravel 10 Collection filter(). We will see the concept of filter items in the Laravel collection. We will filter data into a single-dimensional array, or multi-dimensional array.
We will use Illuminate\Support\Collection class to provide 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: Download Laravel
Let us begin the tutorial by installing a new Laravel application. if you have already created the project, then skip the following step.
composer create-project laravel/laravel example-app
Step 2: Add Controller
php artisan make:controller CollectionController
app/Http/Controllers/CollectionController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CollectionController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$students = collect([
["id" => 1, "name" => "Piyush", "email" => "[email protected]", "marks" => 88],
["id" => 2, "name" => "Pratik", "email" => "[email protected]", "marks" => 70],
["id" => 3, "name" => "Nikhil", "email" => "[email protected]", "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"=>"[email protected]"
"mark"=>88
]
1=>array:4[
"id"=>3
"name"=>"Nikhil"
"name"=>"[email protected]"
"mark"=>75
]
]
I hope it will help you...
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial