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.
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.
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.
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 .
You can use keyBy()
for that:
$result = TestingTable::get()->keyBy('id')->toArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With