我尝试过许多代码变体,并试图在其他主题中找到类似的问题。因此,我有表用户,其中每个用户有一个城市(存储为一个数字),当然,表城市的id和城市的名称(40个城市在那里)。当真正的用户打开他的配置文件设置页面,我希望他的城市被选中并以形式显示。在本例中,用户表中的"Alex“具有城市”2“。在桌面城市: id "2“和name_ru "cityB”。
如果我试试这个:
@foreach(App\City::get() as $city)
<option value='{{ $city->id }}'>{{ $city->name_ru }}</option>
@endforeach它只显示城市,但我需要这样的结果:
<option value="1" > cityA</option>
<option selected value="2" > cityB </option>
<option value="3" > cityC </option>因此,问题是--如何只选择一个标签选项,哪个值等于该城市的数量,该城市的值存储在表用户中,用于"Alex“。
我曾想过,但它没有显示出什么:
@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>请帮帮忙
发布于 2016-12-12 12:41:39
试试这个:
@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() on view这样的模型中获取数据不是一个好主意,相反,在控制器上获取数据并将其传递给视图是正确的方法。
发布于 2016-12-12 12:46:29
您不应该在视图中使用Model查询,因为这是一个不好的实践,因为您没有遵循MVC模式。你可以试试这个:
在您的控制器内:
class UsersController extends Controller {
public function users() {
$users = User::with('city')->get();
$cities = City::all();
return view('view_name', compact('users', 'cities'));
}
}在您的刀片视图中,您可以这样使用ternary operator:
@foreach($users as $user)
<select>
@foreach($cities as $city)
<option value="{{ $city->id }}" {{ ($user->city->id == $city->id) ? 'selected' : '' }}>
{{ $city->name }}
</option>
@endforeach
</select>
@endforeach希望这能有所帮助!
发布于 2016-12-12 12:49:45
<select name="cities" id="cities">
<option value="">Select Cities</option>
@foreach($cities as $city){
<option value="{{$city->id}}{{($result->cityid==$city->id)?'SELECTED':''; ?>">{{$city->name}}</option>
}
@endforeachhttps://stackoverflow.com/questions/41101152
复制相似问题