我有3张桌子:
Type: id, name
Level: id, name
Question: id, content, type_id, level_id
我已经使用“过滤器”按钮完成了过滤器功能。但是现在,我想要的是,当我进行过滤时,无需使用按钮即可将数据自动加载到表中。我该怎么办?
这是我使用按钮的代码
FilterController:
public function filter(Request $request){
$types = Type::all();
$levels = Level::all();
$model = Question::where('id', '>', 0);
if (isset($request->type))
$model = $model->where('type_id', $request->type);
if (isset($request->level))
$model = $model->where('level_id', $request->level);
$data = $model->paginate(999)->appends(request()->query());
return view('filter', compact( 'data', 'request', 'types','levels'));
}
filter.blade.php
<form method="get">
<select name="type">
<option value="">All Types</option>
@foreach ($types as $item)
<option value="{{ $item->id }}" @if ($request->type == $item->id) selected @endif>{{ $item->name }}</option>
@endforeach
</select>
<select name="level">
<option value="">All Levels</option>
@foreach ($levels as $item)
<option value="{{ $item->id }}" @if ($request->level == $item->id) selected @endif>{{ $item->name }}</option>
@endforeach
</select>
<button type="submit" class="btn btn-primary">Filter</button>
</form>
<table border="1">
<tr>
<th>ID</th>
<th>Content</th>
</tr>
@foreach ($data as $q)
<tr>
<td>{{ $q->id }}</td>
<td>{{ $q->content }}</td>
</tr>
@endforeach
</table>
答案 0 :(得分:1)
您可以在选择值更改时简单地提交表单:
<select onchange="this.form.submit()">
...
</select>
或者,如果您不想使用表单,假设您的路径为/questions
,并且在.env文件中设置了APP_URL
属性,则可以执行以下操作:
<select name="type" onchange="window.location.href = this.value">
<option value="{{ url('questions') }}">All types</option>
@foreach($types as $type)
<option value="{{ url('questions') }}?type={{ $type->id }}"{{ request('type') == $type->id ? ' selected' : '' }}>
{{ $type->name }}
</option>
@endforeach
</select>
如果要在按类型过滤时保持当前选定的级别不变,可以将选项值更改为以下内容:
<option value="{{ url('questions') . '?' . (request()->filled('level') ? 'level=' . request('level') . '&' : '') . 'type=' . request('type') }}">
{{ $type->name }}
</option>
在我的手机上回答了该问题,因此语法可能已损坏。