Laravel Collection keyBy() Method Example

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

This lesson is focused on laravel collection keyby lesson. i would like to share with you laravel collection keyby multiple. This article will give you simple lesson of keyby collection laravel lesson. if you have question about laravel collection key by value then i will give simple lesson with solution. Hello Brother, Creating a basic lesson of laravel collection key by index.

The keyBy() method will help to reset key from given collection key.

I will give you simple lesson of keyBy() colletion in laravel. so you can easily use it with your laravel 5, laravel 6, laravel 7 and laravel 8 application. so let's see bellow lesson that will helps you lot.

Syntax:

$collecton->keyBy(

$key_name

);

Lesson 1

public function index()

{

$collection = collect([

["id"=>1, "name"=>"Sagor", "role"=>"Admin"],

["id"=>2, "name"=>"Paresh", "role"=>"Admin"],

["id"=>3, "name"=>"Rakesh", "role"=>"User"],

]);

$output = $collection->keyBy('name');

dd($output);

}

Result:-

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[Sagor] => Array

(

[id] => 1

[name] => Sagor

[role] => Admin

)

[Paresh] => Array

(

[id] => 2

[name] => Paresh

[role] => Admin

)

[Rakesh] => Array

(

[id] => 3

[name] => Rakesh

[role] => User

)

)

)

Lesson 2

public function index()

{

$collection = collect([

["id"=>1, "name"=>"Sagor", "role"=>"Admin"],

["id"=>2, "name"=>"Paresh", "role"=>"Admin"],

["id"=>3, "name"=>"Rakesh", "role"=>"User"],

]);

$output = $collection->keyBy(function ($item) {

return strtoupper($item['name']);

});

dd($output);

}

Result:-

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[HARDIK] => Array

(

[id] => 1

[name] => Sagor

[role] => Admin

)

[PARESH] => Array

(

[id] => 2

[name] => Paresh

[role] => Admin

)

[RAKESH] => Array

(

[id] => 3

[name] => Rakesh

[role] => User

)

)

)

thank you very much for following up with me.

Recent Posts

Related Posts