foreach Laravel-5< option选择 [英] foreach Laravel-5 <option select
问题描述
我尝试了很多代码变体,并试图在其他主题中找到类似的问题.因此,我有表用户,其中每个用户都有一个城市(存储为数字),当然还有具有ID和城市名称的表城市(那里有40个城市).当真实用户打开其个人资料设置页面时,我希望选择并显示其城市.在此示例中,用户表"Alex"中的城市为"2".在表格city中:id为"2",name_ru为"cityB".
I have tried a lot of variants of code and tried to find similar problem in other topics. So, i have table users where each user is having one city(stored as a number), and of course table city with id and name of city (40 cities is there). When real user open his profile settings page I want his city to be selected and and displayed in form. In this example in user table "Alex" is having city"2". In table city: id "2" and name_ru "cityB".
如果我尝试这样做:
@foreach(App\City::get() as $city)
<option value='{{ $city->id }}'>{{ $city->name_ru }}</option>
@endforeach
它仅显示城市,但我需要这样的结果:
It shows only cities, but I need result like this:
<option value="1" > cityA</option>
<option selected value="2" > cityB </option>
<option value="3" > cityC </option>
所以问题是-如何只选择一个标签OPTION,其值等于该城市的编号,该标签存储在表用户中的"Alex".
So the question is - How to make SELECTED only one tag OPTION, which VALUE is equal to number of that city, which is stored in table users for "Alex".
我考虑了一下,但是什么也没显示:
I thought about this, but it shows nothing:
@foreach(App\City::get() as $city)
@if($user->city ==1)
<option selected value="1" > {{ $city->name_ru }}</option>
@elseif($user->city ==2)
<option selected value="2" > {{ $city->name_ru }}</option>
....
@endif
@endforeach
如果我尝试这样做:
@foreach(App\City::get() as $city)
@if($user->city ==1)
<option selected value="1" > {{ $city->name_ru }}</option>
@endif
@endforeach
@foreach(App\City::get() as $city)
@if($user->city ==2)
<option selected value="2" > {{ $city->name_ru }}</option>
@endif
@endforeach
@foreach(App\City::get() as $city)
@if($user->city ==3)
<option selected value="3" > {{ $city->name_ru }}</option>
@endif
@endforeach
我得到:
<option selected value="2" > cityA</option>
<option selected value="2" > cityB</option>
<option selected value="2" > cityC</option>
请帮助
推荐答案
尝试一下:
@foreach(App\City::get() as $city)
$selected = '';
if($city->id == 1) // Any Id
{
$selected = 'selected="selected"';
}
// $selected is initially empty and when the if criteria met it contains selected which make dropdown selected
<option value='{{ $city->id }}' {{$selected}} >{{ $city->name_ru }}</option>
@endforeach
已编辑:在视图上从类似 App \ City :: get()
的模型中获取数据不是一个好主意,而是在控制器上获取并将其传递给视图是正确的方法.
Edited: fetching data from models like App\City::get()
on view is not a good idea, instead fetch it on controller and pass it on to the view is the right way.
这篇关于foreach Laravel-5< option选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!