Eloquent: How to make lists() work for Accessor fields?

A very convenient way to populate dropdown options with Eloquent is to use lists() function. But it doesn't work out of the box with "Append" fields, also called "Accessors". Here's a small trick to make it work. First, how it works in a simple way: Controller:
$employees = Employee::where('branch_id', 9)->lists('name', 'id');
return view('customers.create', compact('employees'));
View:
{!! Form::select('employee_id', $employees, '') !!}
And the result is a dropdown list with employees. Now, what if in your database table employees you have fields "name", "surname" and in Eloquent model you have append field full_name?
public function getFullNameAttribute() {
    return $this->name . ' ' . $this->surname;
}
And if you try to use the same lists('full_name', 'id'), it will fail with this error:
[2015-07-19 21:47:19] local.ERROR: exception 'PDOException'
with message 'SQLSTATE[42S22]: Column not found:
1054 Unknown column 'full_name' in 'field list'' in
...vendor\laravel\framework\src\Illuminate\Database\Connection.php:288
The solution is to first get the results of the query, and only then to add lists() function, like this. Instead of:
$employees = Employee::where('branch_id', 9)->lists('full_name', 'id');
You do:
$employees = Employee::where('branch_id', 9)->get()->lists('full_name', 'id');
And then you would have a proper dropdown, this time with full names. See you in the next Laravel tip!

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by