How to get object values inside array in laravel?

Member

by rollin , in category: Third Party Scripts , 5 months ago

How to get object values inside array in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 5 months ago

@rollin 

To get object values inside an array in Laravel, you can use the Laravel Collection methods to access the values. Here's an example:


Assuming you have an array of objects like this:

1
2
3
4
5
$items = [
    (object) ['id' => 1, 'name' => 'Item 1'],
    (object) ['id' => 2, 'name' => 'Item 2'],
    (object) ['id' => 3, 'name' => 'Item 3'],
];


You can use the pluck method to retrieve values from the objects in the array:

1
$names = collect($items)->pluck('name');


This will give you an array of the names:

1
["Item 1", "Item 2", "Item 3"]


You can also use other Collection methods like map, filter, each, etc. to manipulate and extract values from the objects in the array.