Laravel collection of keys

We use the collect for creating a new collection from array, run the strtoupper function on each element, also remove all empty elements:

In this article I will show you laravel eloquent keys example. We will also implement a laravel keys collection.

The keys() method will help to create new collection of collection keys.

I will give you simple example of keys() colletion in laravel. This works with laravel 5, laravel 6, laravel 7 and laravel 8 applications.

Syntax:

$collecton->keys();

Example

public function index()
{
    $collection = collect([
            "one" => ["id"=>1, "name"=>"Vijay", "role"=>"Admin"],
            "two" => ["id"=>2, "name"=>"Manav", "role"=>"User"],
            "three" => ["id"=>3, "name"=>"Prem", "role"=>"User"],
        ]);
  
    $output = $collection->keys();
   
    dd($output);
  
}

Output

Illuminate\Support\Collection Object

(

    [items:protected] => Array

        (

            [0] => one

            [1] => two

            [2] => three

        )

)

Basics

We’ll use the collect helper to create a new collection instance from the array, run the strtoupper function on each element, and then remove all empty elements:

$collection = collect(['ashish', 'vinod', null])->map(function ($name) {
    return strtoupper($name);
})->reject(function ($name) {
    return empty($name);
});

Creating Collections

As mentioned above, the collect helper returns a new Illuminate\Support\Collection instance for the given array. So, creating a collection is as simple as:

$collection = collect([1, 2, 3]);

Extending Collections

Collections are “macroable”, which allows you to add additional methods to the Collection class at run time. The Illuminate\Support\Collection class’ macro method accepts a closure that will be executed when your macro is called. The macro closure may access the collection’s other methods via $this, just as if it were a real method of the collection class. For example, the following code adds a toUpper method to the Collection class:

use Illuminate\Support\Collection;
use Illuminate\Support\Str;

Collection::macro('toUpper', function () {
    return $this->map(function ($value) {
        return Str::upper($value);
    });
});

$collection = collect(['first', 'second']);

$upper = $collection->toUpper();

// ['FIRST', 'SECOND']

Leave a Comment