如何在选择的 dom 元素中获取选定的值 [Laravel]

有人可以告诉我当我尝试在 Laravel 项目中编辑帖子时如何获得选定的值。 所以这里有部分代码


后.php:


public function category(){

    return $this->belongsTo('App\Category');

}

类别.php:


public function posts(){

    return $this->hasMany('App\Post');

}

后控制器.php:


 $post = Post::findOrFail($id);

 $categories = Category::all();

 $tags = Tag::all();

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

帖子/edit.blade.php:


<div class="form-group">

        <label for="category_id">Selecet category</label>

        <select name="category_id" id="category_id" class="form-control">

            <option disabled>List of available post categories</option>

            @foreach($categories as $category)


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


            @endforeach

        </select>

    </div>


人到中年有点甜
浏览 107回答 2
2回答

慕桂英4014372

这部分代码解决了问题(对于将来会阅读本文的用户:))@foreach($categories as $category)&nbsp; &nbsp; <option value="{{ $category->id }}"&nbsp; &nbsp; &nbsp; &nbsp; @if($post->category->id == $category->id)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;selected&nbsp; &nbsp; &nbsp; &nbsp; @endif&nbsp; &nbsp; >{{ $category->name }}</option>@endforeach

子衿沉夜

$category->id == $category->id将始终返回 true。实际上,如果你只是想从表单提交中获取值。你可以删除它。HTML 将自行处理所选值。您可以简单地$request->category_name在后端使用。
打开App,查看更多内容
随时随地看视频慕课网APP