I'm trying to show the selected category in the edit form But it is not showing,
My view :
<select name="category_id" id="category_id" class="form-control{{ $errors->has('category_id') ? ' is-invalid' : '' }}">
{{--<option value="">Choose Category</option>--}}
@foreach($cat as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
@endforeach
</select>
the edit method in my PostController
:
public function edit($id)
{
$post = Post::findOrFail($id);
$cat = Category::all();
return view('admin.posts.edit',['post'=>$post,'cat'=>$cat]);
}
I tried to put an if statement like this :
@foreach($cat as $category)
<option value="{{ $category->id }}" {{$category->id == App\Category::class ? 'selected="selected"' : '' }}>{{ $category->name }}</option>
@endforeach
It is showing a category However it's not the selected category for the post.
HELP
$category->id == App\Category::class
You're comparing the id of the category with the name of the class here.
What you want to do is probably this:
$category->id == $post->category_id
check request by category id and if it is same echo selected.
@foreach($cat as $category) <option value="{{$category->id}}" @if(request()->category_id==$category->id) selected @endif>{{$category->name}}</option> @endforeach
Just retrieve it as a the defined select:
<select name="category_id" id="category_id" class="form-control{{ $errors->has('category_id') ? ' is-invalid' : '' }}">
<option value="{{ post->category->id }}" name="{{ $post->category->name }}">
@foreach($cat as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
@endforeach
</select>
This will now be the default option and the loop will still be in the dropdown