编辑帖子时获取选择选项

时间:2018-06-17 08:41:27

标签: php laravel

我试图在编辑表单中显示所选类别但它没有显示,

我的观点:

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

我的PostController中的编辑方法:

 public function edit($id)
    {
        $post = Post::findOrFail($id);
        $cat = Category::all();

        return view('admin.posts.edit',['post'=>$post,'cat'=>$cat]);
    }

我试着写一个这样的if语句:

  @foreach($cat as $category)
                        <option value="{{ $category->id }}" {{$category->id == App\Category::class ? 'selected="selected"' : '' }}>{{ $category->name }}</option>

                    @endforeach

它显示的是一个类别但是它不是该帖子的选定类别。

HELP

3 个答案:

答案 0 :(得分:0)

按类别ID检查请求,是否选择了相同的回显。

@foreach($cat as $category) <option value="{{$category->id}}" @if(request()->category_id==$category->id) selected @endif>{{$category->name}}</option> @endforeach

答案 1 :(得分:0)

只需将其检索为已定义的选择:

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

这将是默认选项,循环仍将在下拉列表中

答案 2 :(得分:0)

$category->id == App\Category::class

您将此类别的ID与此类名称进行比较。

你想做的可能就是:

$category->id == $post->category_id