Laravel 4: Using query builder lists for Form::select

Recently I realised I’ve been doing the wrong way to populate the array for Form::select().

In order to get Form::select() to work, the array you parse in must contain key => value. So in the past, I’ve been doing it this way:

$select_array = array();
foreach (Classname::all() as $model) {
    $select_array[$model->id] = $model->name;
}

It does the work, but there’s a built-in function in Laravel that can do this (probably faster, I think) in just 1 line:

$select_array = Classname::lists('name', 'id');

It returns an array that will work with Form::select().

This function is mentioned in the Laravel Documentation to retrieve specific column from a model. But it wasn’t clear that it’s also useful to populate an array for Form::select().

Advanced level

What if the value you want to get is in another class that’s related to this class? Well, we can combine join() with select() and then list().

For example:

$select_array = ModelOne::join('modeltwos', 'modeltwos.id', '=', 'modelones.modeltwo_id')
 ->select('modeltwos.name', 'modelones.id')
 ->lists('name', 'id');

I hope this is useful. Do leave a comment if you have a better way of populating the array for Form::select().


3 Comments

  • larry

    February 5, 2015

    Hey Andrew, I just contacted you through Twitter requesting your help perfecting a query. This was a great piece. Thanks for sharing.

    Reply
  • larry

    February 28, 2015

    This tutorial was extremely helpful and lead me to success in my first full scale application. A million to Andrew’s blog.

    Reply
  • steeveave

    May 1, 2015

    Good Information,Very Thanks

    UK Largest Web Design Company

    Reply

Leave a Reply