Create dropdown using lists() method to get two columns and combine them in final view

I was working with dropdowns and was thinking if it is possible to use lists() method to get two columns and join them together? Say I have a first_name and last_name, so I would like to make the dropdown with both first_name and last_name comibned and displayed as name with the id as the value. Is it possible to do with lists() method? If yes, how? If no, what are other alternatives other than building the array myself?

jayhealey replied 3 years ago

You should be able add an alias via a SELECT clause to the columns you want to join up, and then reference that in the LISTS() call.

$list = MyModel::select(
        DB::raw("(first_name +' '+ last_name) AS full_name, id")
    )->lists('full_name', 'id');

I can't remember the order of the key/value for LISTS(), but that should do it.

v2techlabs replied 3 years ago Solution


Thanks for the pointer. I needed to make some changes and this works fine for me:

DB::raw("CONCAT(first_name,' ', last_name) AS full_name, id")

But thanks for pointing me in the right direction.

juancho48 replied 3 years ago

You should always create your queries on mysql and make sure thy work it should be something like this

CONCAT(first_name, ' ', last_name) AS full_name, id ( note that there's a space between the 2 single quotes), then make it work the laravel way

polarix2017 replied 1 year ago

This does not works (L5.2) in a {!! Form::select !!}}.

While in tinker has the right answare, i obtain an empty list (only "option value=" is set ti ID) in the select control tag:

{!! Form::select('driver_id',  App\Driver::select(DB::raw("CONCAT(first_name,' ', last_name) AS full_name, id"))->pluck('full_name','id'), null, ['class' => 'form-control'])  !!} 

Why ? Thank you.

Sign in to participate in this thread!

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