Laravel 8中如何保持下拉筛选框选中选项的状态?
评论筛选下拉框"全部评论"选项无法保持选中的问题
背景
我用Laravel 8开发了一个博客应用,文章支持评论功能,评论需经管理员审核后才可发布。我添加了一个下拉选择框,用于按状态筛选评论或显示全部评论:
<form class="d-flex align-items-center" method="get" action="{{ route('dashboard.comments')}}"> <label for="commentsFilter" class="form-label mb-0 me-1">Filter</label> <select class="form-select" id="commentsFilter" name="filter" onchange="this.form.submit()"> @foreach ($filters as $filter) <option value="{{ $filter->value }}" {{ $active_filter == $filter->value ? 'selected' : '' }}>{{ $filter->label }}</option> @endforeach </select> </form>
控制器代码
CommentController的index方法代码如下:
class CommentController extends Controller { public function index(Request $request) { // 评论总数 $comments_count = Comment::count(); // 未审核评论数 $unapproved_comments_count = Comment::where('approved', 0)->count(); // 每页显示评论数 $per_page = 10; // 筛选选项 $filters = $filter = [ (object)[ 'value' => 'all', 'label' => 'All comments' ], (object)[ 'value' => 0, 'label' => 'Unapproved' ], (object)[ 'value' => 1, 'label' => 'Approved' ] ]; // 从URL获取当前筛选器 $active_filter = $request->query('filter'); // 按筛选条件获取评论 $filter = $request->input('filter'); $comments = Comment::orderBy('id', 'desc') ->when($filter !== 'all', function ($query) use ($filter) { return $query->where('approved', $filter); }, function ($query) { return $query->where('approved', 1)->orWhere('approved', 0); }) ->paginate($per_page)->onEachSide(1); return view( 'dashboard/article-comments', [ 'per_page' => $per_page, 'current_page' => $comments->currentPage(), 'comments' => $comments, 'comments_count' => $comments_count, 'unapproved_comments_count' => $unapproved_comments_count, 'filters' => $filters, 'active_filter' => $active_filter, ] ); } }
问题
当选择查看全部评论时,<option value="all">All comments</option>选项无法保持选中状态,但另外两个选项选择后可以正常保持选中。我尝试修改获取活跃筛选器的代码为以下内容,但仍然无效:
// 从URL获取当前筛选器 if (isset($active_filter) && !is_null($active_filter)) { $active_filter = $request->query('filter'); } else { $active_filter = 'all'; }
请问如何在URL为dashboard/comments?filter=all时,保持「All comments」选项处于选中状态?
内容的提问来源于stack exchange,提问作者Razvan Zamfir
相关产品推荐
相关产品推荐

