我一直在 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 控制器中,我有:
class CommentController extends Controller
{
public function index(Request $request)
{
// Total number of comments
$comments_count = Comment::count();
// Total number of unapproved comments
$unapproved_comments_count = Comment::where('approved', 0)->count();
// Comments per page
$per_page = 10;
// Comments filters
$filters = $filter = [
(object)[
'value' => 'all',
'label' => 'All comments'
],
(object)[
'value' => 0,
'label' => 'Unapproved'
],
(object)[
'value' => 1,
'label' => 'Approved'
]
];
// Get active filter from URL
$active_filter = $request->query('filter');
// Comments (with 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,
]
);
}
}
当我选择查看所有评论(来自
<select>
元素)时,<option value="all">All comments</option>
不会保持选中状态(而其他 2 个选项在选择时仍保持选中状态)。
dashboard/comments?filter=all
时,如何保持“所有评论”选项处于选中状态?dashboard/comments
时怎么办?在选项标签中使用 if 语句,如下所示:
<option value="{{ $filter->value }}" @if($active_filter == $filter->value) selected @endif }}>{{ $filter->label }}</option>