简体   繁体   中英

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?

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');

尝试采用方法

Form::select('size', $suppliers->pluck('name', 'id')->all())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM