首页 > 解决方案 > 在 Laravel 中不使用按钮和 ajax 自动过滤

问题描述

我有 3 张桌子:

Type: id, name
Level: id, name
Question: id, content, type_id, level_id

我已经用“过滤器”按钮完成了过滤功能。但是现在,我想要的是,当我过滤时,数据会自动加载到表中,而无需使用按钮。我能怎么做?

这是我使用按钮的代码

过滤控制器:

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'));
    }

过滤器.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>

标签: mysqllaravel

解决方案


当您的选择值更改时,您可以简单地提交表单:

<select onchange="this.form.submit()">
    ...
</select>

或者,如果您不想使用表单,假设您的路径是/questions并且您已经APP_URL在 .env 文件中设置了属性,您可以执行类似于以下的操作:

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

在我的手机上回答,所以可能有语法错误。


推荐阅读