0

I solver this by this code

    $service_list = Service::all();
    $services = [];
    foreach ($service_list as $item){
        $services[$item['id']] = $item['name'];
    }

but how to do that using php_array functions? its for dropdown select

3 Answers3

3

Not sure why you have to use PHPs built in array methods but we have pluck on the Query Builder and Collection class.

$services = Service::pluck('name', 'id');
// $services->all(); // for the actual array contained

This will only select the name and id in the query and give you a Collection keyed by the id only containing the name field.

$services = Service::all();
$services_array = $services->pluck('name', 'id')->all();

If you already have your collection of models (code above has queried for every field and hydrated models with the result) you can use pluck on the Collection to achieve the same result (though less efficient as it had to query for all fields, hydrate models, then pull those 2 fields from them)

Laravel 5.5 Docs - Query Builder - Retrieving Results

Laravel 5.5 Docs - Collections - pluck method

lagbox
  • 48,571
  • 8
  • 72
  • 83
1

Use toArray() to convert the collection to an array, then use array_combine() to create an associative array from that.

$service_list = Service::all()->toArray();
$services = array_combine(array_column($service_list, 'id'), array_column($service_list, 'name'));
Barmar
  • 741,623
  • 53
  • 500
  • 612
0
$service_list = Service::all()->toArray();

all() will return a collection. The collection supports a toArray() method

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110