Hello all!
Currently I have an application where I have stored in the database the following columns for icons table: [id | name | path].
Very simple. It referers to icons I'll be using through the whole app. The "name" column I have associated to the field_names of another table. Those icons represent those columns.
What I want, is to know if Eloquent provides some way to return an array where I can specify the key. In this case it would be the column "name".
With Icons::all()->toArray() returns.
array (size=15)
0 =>
array (size=4)
'id' => int 1
'path' => string 'imagens/imagens/estacao_bateria.png' (length=35)
'name' => string 'bateria' (length=7)
'descricao' => string 'Icone da bateria' (length=16)
1 =>
array (size=4)
'id' => int 2
'path' => string 'imagens/imagens/estacao_chuva.png' (length=33)
'name' => string 'chuva' (length=5)
'descricao' => string 'Icone da zzzz' (length=13)
I want a way it will return this:
array (size=15)
'bateria' =>
array ()
'path' => string 'imagens/imagens/estacao_bateria.png' (length=35)
'descricao' => string 'Icone da bateria' (length=16)
'chuva' =>
array ()
'path' => string 'imagens/imagens/estacao_chuva.png' (length=33)
'descricao' => string 'Icone da zzzz' (length=13)
Thanks!
You should consider overriding the toArray()
method in your collection class.
It should be pretty easy to implement.
<?php namespace Extensions;
class CustomCollection extends \Illuminate\Database\Eloquent\Collection {
public function toArray()
{
// ...Your own implementation...
}
}
class Icons extends Eloquent {
// Override the parent method
public function newCollection(array $models = Array())
{
return new Extensions\CustomCollection($models);
}
}
You can do:
Icon::all()->keyBy('name')
or
Icon::all()->keyBy('name')->toArray()
arjan said:
You can do:
Icon::all()->keyBy('name')
or
Icon::all()->keyBy('name')->toArray()
Perfect!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community