Search code examples
phplaravellaravel-4laravel-bladeformbuilder

Laravel 4 display list of data into form selection


How do I display a list of books in laravel form builder selection?

BookController.php

$book_names = Book::all();

return View::make('books')->with('book_names', $book_names);

At the moment I only know how do manually input data:

{{ Form::select('book_name', array(
  'book1' => 'book1', 
  'book2' => 'book2', 
  'book3' => 'book3') 
}}

I want to do something like this:

{{ Form::select('book_name', array(
  @foreach($book_names as $book_name)
    $book_name->name => $book_name->name, 
  @endforeach 
}}

But obviously It won't work..


Solution

  • Meet the lists() method. It allows you to create an array from one or two (key and value) properties of a collection:

    $book_names = Book::lists('name');
    
    return View::make('books')->with('book_names', $book_names);
    

    And then simply pass that array:

    {{ Form::select('book_name', $book_names) }}