Support the ongoing development of Laravel.io →
Database Eloquent Installation

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!

Last updated 2 years ago.
0

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);
    }
}

Last updated 9 years ago.
0
Solution

You can do:

Icon::all()->keyBy('name')

or

Icon::all()->keyBy('name')->toArray()
0

arjan said:

You can do:

Icon::all()->keyBy('name')

or

Icon::all()->keyBy('name')->toArray()

Perfect!

0

Sign in to participate in this thread!

Eventy

Your banner here too?

resmall resmall Joined 24 Aug 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.