Home > Mobile >  Laravel Pluck and combine two fields to generate a select menu
Laravel Pluck and combine two fields to generate a select menu

Time:07-21

Let's say I have the following fields in my database for a user, id, first_name and last_name. I want to generate a select menu, something like below:

<select>
    <option value="id">first_name   last_name</option>
</select>

I know I can use pluck to get an array with id as the key and one more field as the value:

User::pluck('first_name', 'id')->all();

And this would produce:

array:4 [▼
  1 => "John"
  2 => "Linda"
  3 => "Jane"
  4 => "Carl"
]

Is there an easy way using eloquent to get the first_name AND the last_name so I can get the following:

array:4 [▼
  1 => "John Doe"
  2 => "Linda Smith"
  3 => "Jane Doe"
  4 => "Carl Johnson"
]

The first_name and last_name are examples to explain my question, I need to combine two other fields instead which cannot be 'merged' into one field.

CodePudding user response:

Best way to do this is to append the model attribute on fly get full name.

In Model

class User extends Model
{
   public $appends = [ 'full_name' ];

   public function getFullNameAttribute()
   {
      return $this->first_name .' '. $this->last_name;
   }
}

In Controller

User::pluck('full_name', 'id')->all();

If you are using Laravel latest version, follow this as well https://laravel.com/docs/9.x/eloquent-serialization#appending-values-to-json

  • Related