显示所选类别
Show selected category
如何在我的 edit.blade.php 中显示我选择的产品类别。您只能选择 1 个类别,因此不是多对多关系。
产品型号:
public function category(){
return $this->belongsTo(Category::class);
}
类别模型:
public function products(){
return $this->hasMany(Product::class);
}
数据库产品:
<div class="form-group my-2">
<label for="category">Choose Category :</label>
<select name="category_id" class="form-control custom-select">
@foreach($categories as $category)
<option value="{{$category->id}}" @if($product->category->contains($category->id)) selected @endif>{{$category->name}}</option>
@endforeach
</select>
</div>
我不断收到如下错误:
调用未定义的方法 App\Models\Category::contains()
您的产品belongsTo
类别:
<option value="{{$category->id}}" @if($product->category_id == $category->id) selected @endif>{{$category->name}}</option>
你可以试试这个
<option value="{{$category->id}}" {{($product->category_id == $category->id) ? 'selected' : ''}}>{{$category->name}}</option>
Laravel 版本 < 9
<option value="{{ $category->id }}" {{ ($product->category_id == $category->id) ? 'selected' : '' }}>{{ $category->name }}</option>
幼虫版本 > 9
<option value="{{ $category->id }}" @selected($product->category_id == $category->id)>{{ $category->name }}</option>
Ref: https://laravel.com/docs/9.x/blade#checked-and-selected
如何在我的 edit.blade.php 中显示我选择的产品类别。您只能选择 1 个类别,因此不是多对多关系。
产品型号:
public function category(){
return $this->belongsTo(Category::class);
}
类别模型:
public function products(){
return $this->hasMany(Product::class);
}
数据库产品:
<div class="form-group my-2">
<label for="category">Choose Category :</label>
<select name="category_id" class="form-control custom-select">
@foreach($categories as $category)
<option value="{{$category->id}}" @if($product->category->contains($category->id)) selected @endif>{{$category->name}}</option>
@endforeach
</select>
</div>
我不断收到如下错误: 调用未定义的方法 App\Models\Category::contains()
您的产品belongsTo
类别:
<option value="{{$category->id}}" @if($product->category_id == $category->id) selected @endif>{{$category->name}}</option>
你可以试试这个
<option value="{{$category->id}}" {{($product->category_id == $category->id) ? 'selected' : ''}}>{{$category->name}}</option>
Laravel 版本 < 9
<option value="{{ $category->id }}" {{ ($product->category_id == $category->id) ? 'selected' : '' }}>{{ $category->name }}</option>
幼虫版本 > 9
<option value="{{ $category->id }}" @selected($product->category_id == $category->id)>{{ $category->name }}</option>
Ref: https://laravel.com/docs/9.x/blade#checked-and-selected