How to get the specific array from collection in laravel?

by aniya.jaskolski , in category: PHP Frameworks , 5 months ago

How to get the specific array from collection in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 5 months ago

@aniya.jaskolski 

To get a specific array from a collection in Laravel, you can use the pluck method. This method allows you to retrieve a specific column from the collection as an array.


Here's an example:

1
2
3
4
5
6
7
8
9
$collection = collect([
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 25],
    ['name' => 'Mike', 'age' => 35]
]);

$names = $collection->pluck('name')->toArray();

// $names is now ['John', 'Jane', 'Mike']


In this example, the pluck method is used to retrieve the "name" column from the collection as an array. The toArray method is used to convert the collection into a plain PHP array.


You can also specify multiple columns to retrieve as an array by passing an array of column names to the pluck method:

1
2
3
$data = $collection->pluck(['name', 'age'])->toArray();

// $data is now [['name' => 'John', 'age' => 30], ['name' => 'Jane', 'age' => 25], ['name' => 'Mike', 'age' => 35]]


This will return an array of arrays, each containing the specified columns.