@oxbir try this
<option value="{{ $category->id }}" {{ $product->category_id == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I want to retrieve database values in category name and i want to show default value in selection. This is my controller for my edit view.
I have a category_product table.
<div class="col-md-4">
<div class="form-group">
<label for="category">category</label>
<select class="form-control" name="category" id="category">
@foreach($categories as $category)
<option value="{{ $category->id }}" {{ $product->categories()->category_id == $category->id ? 'selected' : '' }}>{{ $category->name }}</option>
@endforeach
</select>
</div>
</div>
ProductController.php
public function edit(Product $product)
{
$categories = Category::all();
return view('Admin.products.edit', compact('product', 'categories'));
}
Product.php
public function categories()
{
return $this->belongsToMany(Category::class);
}
I get this error.
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$category_id
Since the Product can have many Categories per your relationship and the pivot table implication, you would have to use an in_array method (or something similar) like:
@foreach($categories as $category)
<option value="{{ $category->id }}" {{ (in_array($category->id, $product->categories->pluck('id')->toArray()) ? 'selected' : '' }}>{{ $category->name }}</option>
@endforeach
Does each Product possibly belong to many different Categories? Or does each Product belong to one Category? Because if the later is true, then you would have to adjust your relationship to a oneToMany as opposed to the current manyToMany with the pivot table.
Please or to participate in this conversation.