mpen
mpen

Reputation: 282895

Laravel fetch numeric?

How can I fetch an array of numeric arrays in Laravel?


Here's what I've got:

 $companies = Company::select(['id','name'])->get()->toArray();

This gives me back:

array:21 [
    0 => array:2 [
      "id" => 21
      "name" => "Cool Company"
    ]
    1 => array:2 [
      "id" => 4
      "name" => "Bacon Co"
    ]
    ....

But I want:

array:21 [
    0 => array:2 [
      21,
      "Cool Company"
    ]
    1 => array:2 [
      4,
      "Bacon Co"
    ]
    ....

Upvotes: 0

Views: 158

Answers (1)

peterm
peterm

Reputation: 92785

If you need this exact output you can do

$companies = App\Company::pluck('name', 'id')
    ->map(function ($name, $id) { 
        return [$id, $name]; 
    })
    ->values()
    ->toArray();

Output:

=> [
     [
       4,
       "Bacon Co",
     ],
     [
       21,
       "Cool Company",
     ],
   ]

Not sure what you're doing with it afterwards but maybe just the output of pluck() will suffice

$companies = App\Company::pluck('name', 'id')->toArray();
=> [
     4 => "Bacon Co",
     21 => "Cool Company",
   ]

Upvotes: 1

Related Questions