Search code examples
laravellaravel-query-builderlaravel-5.7laravel-collection

Question About Pluck Results in Laravel 5.7


I have a question about the pluck method in Laravel. How can I get the following result in a list?

Name + Lastname + id

I use this line command in a controller

Line: $choferes

public function index()
{
    $asignaciones = Asignacion::orderBy('id', 'ASC')->get();
    $choferes = Chofer::orderBy('id', 'ASC')->pluck('nombre', 'id');
    $dueños = Dueño::orderBy('id', 'ASC')->pluck('nombre', 'id');
    $asignaciones->each(function ($asignaciones)
    {
        $asignaciones->chofer;
        $asignaciones->dueno;
    });

    return view('admin.asignaciones.index')
        ->with('asignaciones', $asignaciones)
        ->with('choferes', $choferes)
        ->with('dueños', $dueños);
}

The result in a list:

1 => "name 1"
2 => "name 2"

However, I need to combine: name and lastname. It needs to be a list. How can I display it in my view?

<div class="col-xs-6">
    {!! Form::label('chofer_id','Lista de Choferes') !!}
    {!! Form::select('chofer_id[]', $choferes, null,
        ['class'=>'form-control select_chofer',
        'multiple',
        'required','id'=>'list_chofer']) !!}
</div>

I have this result:

result

Thanks!


Solution

  • In your Chofer model define

    public funcion getFullNameAttribute()
    {
        return $this->attributes['first_name'] + ' ' + $this->attributes['last_name'];
    }  
    

    In controller use this

    $choferes = Chofer::orderBy('id', 'ASC')->get(['id`, ...])->pluck('full_name', 'id');