简体   繁体   中英

Laravel-4 Blade: making a form select box using values in an object

I wish to make a select box of city names for a form. I have been able to create and pass to my view an object $city whose values I can correctly list on my view if I simply display them outside of a form. The two properties of $city that are needed for the select box are: $city->id and $city->name.

My attempts to do this using Blade are failing. The issue boils down to: how do I nest @foreach inside of the Blade Form::select statement? For example, without the @foreach, just plunking in a couple of cities, this works perfectly, including a choice of blank, and a default of Albuquerque:

{{ Form::open() }}
{{ Form::Label('city_bldg_id','City:') }}
{{ Form::select('city_bldg_id', array(
    '',
    '2'=>'Albuquerque',
    '11'=>'Bernalillo'
    ),'2') }}
{{ Form::close() }}

In order to populate the select box with all of the values in $city, it would seem that I need to use @foreach inside of the Form::select array. Is this possible to do? If so, how? All of my attempts yield syntax errors. Or, must $city be an array and not an object?

I am so close I can taste it, but I can't figure out the last step. Any suggestions for the appropriate code would be greatly appreciated. Thanks!

I generally prefer creating the select data before going to the view. It's easier to read if it's just

{{ Form::select('city_bldg_id', $cities, '2' }}

(Side note: not sure if you need to enclose the 2 in quotes. Probably not.)

That way, you can do foreaches all you want in order to create the array, and you can do it in pure PHP instead of in Blade.

One simply way to create the array if you're getting the data from an Eloquent model, eg City , is the lists() method:

$cities = City::lists('name', 'id');

If you need to filter out specific cities, you just do it the normal way:

$cities = City::where('somefield', '=', 'value')-> etc... ->lists('name', 'id');

(I hope I'm not assuming too much about what you know already. If this seems too beginnerish and it doesn't help you, I apologise.)

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