Framework: [5.4] Update Collection get method to use Arr helper class.

Created on 31 Mar 2017  路  3Comments  路  Source: laravel/framework

  • Laravel Version: 5.4.16
  • PHP Version: 7.0.8-2
  • Database Driver & Version: MySQL - Ver 14.14 Distrib 5.7.17

Description:

If you have an array within an array and you want to get a value from it you are unable to due to the get method not using the Arr helper class.

Steps To Reproduce:

  • Basic Laravel installation
  • Change routes/web.php to the following:
<?php

use Illuminate\Support\Arr;

Route::get('/', function () {
     $array = [
        'hello' => [
            'world' => 'abc123'
        ]
    ];

    $collection = collect($array)->get('hello.world');
    $array = Arr::get($array, 'hello.world');

    dd($collection, $array); // will return null, abc123
});

To Fix This Issue:

Change the get method to:

public function get($key, $default = null)
{
    return Arr::get($this->items, $key, $default);
}

Most helpful comment

Just hit this same problem, no consistency here.

All 3 comments

@themsaid Could we have more information about why you don't want that?

Several issues and PR about that was closed, and I can't understand why Collection::get() should be different than Arr::get().

Lot of methods in Collection use data_get, so we can use dot notation in where, or pluck but not in has or get??

It feels weird..!

Just hit this same problem, no consistency here.

Collection is an object that gives you extra powers in dealing with arrays, there's no need
to mix functions that deal with pure arrays.

Collection implements ArrayAccess, so you can do array_get on a Collection.

$collection = collect([
    'firstLevel' => 'valueFirstLevel',
    'multi' => [
        'value' => 'yea'
    ], 
]);

array_get('multi.value', $collection); // 'yea'
Was this page helpful?
0 / 5 - 0 ratings

Related issues

RomainSauvaire picture RomainSauvaire  路  3Comments

CupOfTea696 picture CupOfTea696  路  3Comments

PhiloNL picture PhiloNL  路  3Comments

SachinAgarwal1337 picture SachinAgarwal1337  路  3Comments

shopblocks picture shopblocks  路  3Comments