5
votes

Let say I got a table in MySQL database like this, with id the primary key.

--------------------
|id | name | score |
--------------------
 1    Alice   77
--------------------
 2    Bob     89
--------------------
 3    Charlie 95

When using laravel eloquent to get the data from the table,

$result = TestingTable::get()->toArray();
return $result;

The return results is something like this:

{
   0: {
      id: 1,
      name: Alice,
      score: 77,
   },
   1: {
      id: 2,
      name: Bob,
      score: 89,
   },
   2: {
      id: 3,
      name: Charlie,
      score: 95,
   }
}

Is there a function so that the return array will be like:

{
   1: {
      name: Alice,
      score: 77,
   },
   2: {
      name: Bob,
      score: 89,
   },
   3: {
      name: Charlie,
      score: 95,
   }
}

In other words, do I have a way to make the primary key as the index of the return array?

I know I can get what I want by looping through the data and build my own array. I know I can write my own function and call it when I want. I just want to know if there are pre-built function in Laravel or PHP before writing one.

1

1 Answers

12
votes

You can use keyBy() for that:

$result = TestingTable::get()->keyBy('id')->toArray();