Skip to main content
Tutorial Free

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

July 17, 2015
2 min read
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!

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.