Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use primary key as index when getting results using Eloquent of Laravel?

Tags:

php

laravel

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.

like image 619
cytsunny Avatar asked Feb 17 '15 10:02

cytsunny


People also ask

Is eloquent an ORM?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.

What is fillable in Laravel?

The fillable property is used inside the model. It takes care of defining which fields are to be considered when the user will insert or update data. Only the fields marked as fillable are used in the mass assignment. This is done to avoid mass assignment data attacks when the user sends data from the HTTP request.

Is null Laravel eloquent?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .


1 Answers

You can use keyBy() for that:

$result = TestingTable::get()->keyBy('id')->toArray();
like image 134
lukasgeiter Avatar answered Oct 10 '22 13:10

lukasgeiter