Laravel - pluck mutated attribute

You can query with eloquent and use

$limited_select = User::all(['id', 'first_name', 'last_name']);
$limited_select = array_flip($limited_select);

I assumed you wanted to prevent a select * when possible.

generating the select you can do something like this in blade:

<select>
    @foreach($limited_select as $user)
        <option value={{$user->id}}> {{$user->getNameAttribute() }} </option>
    @endforeach
</select>

This would work because getNameAttribute() inside your User Model wil act as an accessor.

Your second option could be using a raw query that has a concat, but I think the eloquent way is more elegant.


I was looking for an answer to this and ended up with a different result so I thought I'd share.

User::get()->pluck('name');

If you get the object first, your mutated attribute will be accessible.


You can dynamically append the attribute to the objects in your collection:

$users->each(function ($model) { $model->setAppends(['name']); });
$users->pluck('name');

This has the nice advantage of not requiring 'name' always be part of your array data, while allowing your collection to use name just in time.