5

If I build a collection from an array:

$collection = collect(['name' => 'john', 'age' => '20']);

How can I access it like you access models, e.g.

$collection->name; //john

I'm having to use $collection['name'].

Is there a way to access it with arrows?

panthro
  • 22,779
  • 66
  • 183
  • 324

2 Answers2

7

Use the get() method:

$value = $collection->get('name');

Full details at https://laravel.com/docs/5.8/collections#method-get.

Tim Rogers
  • 426
  • 5
  • 14
6

use can used like that also

convert array to object

$collection = (object) collect(['name' => 'john', 'age' => '20'])->all();

$collection->name;
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57