Search code examples
phpmysqllaravellaravel-5.3

Laravel: Populate Form dropdown from database


First Laravel Project.

I want to make a form drop-down list what is populated from mysql database. I found this on the documentation:

Form::select('size', array('L' => 'Large', 'S' => 'Small'))

and I tried this:

{{Form::select('size', array(
                @foreach ($suppliers as $supplier)
                $supplier->id => $supplier->name
                @endforeach
))
}}

But I got syntax error:

ErrorException in e34a9587ee23853b6d4c489cc0ed13515fad9c06.php line 23: Parse error: syntax error, unexpected '<', expecting ')' (View: /var/www/html/project/laravel/leltar/resources/views/invoice.blade.php)

What did I wrong?


Solution

  • Pluck returns a collection from laravel version 5.3 and that answer is wrong, it wont show the select box right!

    Here is the right solution!

    $suppliers = Supplier::pluck('name', 'id')->toArray();
    

    and in view call it like this:

    {!! Form::select('supplier', $suppliers, null, ['class' => 'form-control']) !!}
    

    update for Laravel 5.5

    Just tested this and in Laravel 5.5 pluck() works without appending toArray() on it like this:

    $tags = Tag::pluck('name', 'id');
    

    or for this question;

    $tags = Supplier::pluck('name', 'id');