Home > Enterprise >  Show selected category
Show selected category

Time:04-12

How can i show in my edit.blade.php the selected category of my product. you can only choose 1 category so is not many to many relation.

Product model :

   public function category(){
    return $this->belongsTo(Category::class);
}

Category model :

  public function products(){
    return $this->hasMany(Product::class);
}

Db products: enter image description here

<div >
 <label for="category">Choose Category  :</label>
 <select name="category_id" >
  @foreach($categories as $category)
   <option value="{{$category->id}}" @if($product->category->contains($category->id)) selected @endif>{{$category->name}}</option>
  @endforeach
 </select>
</div>

I keep getting errors like : Call to undefined method App\Models\Category::contains()

CodePudding user response:

Your product belongsTo category:

<option value="{{$category->id}}" @if($product->category_id == $category->id) selected @endif>{{$category->name}}</option>

CodePudding user response:

You could try this

 <option value="{{$category->id}}" {{($product->category_id == $category->id) ? 'selected' : ''}}>{{$category->name}}</option>

CodePudding user response:

Laravel version < 9

<option value="{{ $category->id }}" {{ ($product->category_id == $category->id) ? 'selected' : '' }}>{{ $category->name }}</option>

Larvel version > 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

  • Related