JasonDavis
JasonDavis

Reputation: 48933

Laravel 4 Populate a Dropdown list with 2 Database Columns?

echo Form::select(
    'campaign_user_id',
    User::find(1)->profile->lists('first_name', 'id'),
    Input::get('campaign_user_id', $campaign->user_id),
    array(
      "placeholder" => "US",
      'class' => 'form-control',
      'disabled' => 'disabled'
    )
)

The code above is used to build a Dropdown selection list. It fetches a list of Users from the database. On line 3 you can see User::find(1)->profile->lists('first_name', 'id')

It is getting the first_name column, I need to somehow get first and last name columns though and combine them in this list. So that list value is still user ID and Full name is shown.

Any idea how to make this work with 2 DB columns first_name and last_name? Or another method to reach my end goal?

Upvotes: 4

Views: 1375

Answers (1)

Lucky Soni
Lucky Soni

Reputation: 6878

// In your model

class User extends Eloquent
{
    public function getFullNameAttribute()
    {
        return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
    }
}

then grab like so:

User::find(1)->profile->lists('full_name', 'id');

OR

User::find(1)->profile->select(DB::raw('concat (first_name," ",last_name) as full_name,id'))->lists('full_name', 'id');

I prefer the first one :)

Upvotes: 6

Related Questions