You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Backpack CRUD:如何根据status字段过滤select2_from_ajax输出

如何在Laravel Backpack中根据status字段过滤select2_from_ajax的选项?

可以实现,分以下两步操作:

1. 前端给select2请求动态传递status参数

修改setupCreateOperation方法中service_id字段的配置,添加data属性,通过JS实时获取当前status选择框的选中值,随请求传递给后端;同时可以给status字段添加onchange事件,实现切换状态时自动刷新service_id的选项:

public function setupCreateOperation()
{
    ...
    $this->crud->addFields([
        [
            'name'    => 'status',
            'label'   => trans($this->trans_prefix . 'status'),
            'type'    => 'select_from_array',
            'options' => [
                0 => 'one',
                1 => 'two'
            ],
            // status切换时自动重置并刷新service_id选项
            'wrapper' => [
                'attributes' => [
                    'onchange' => "$('select[name=service_id]').val(null).trigger('change');"
                ]
            ]
        ],
        [
            'name'                    => 'service_id',
            'label'                   => trans($this->trans_prefix . 'service'),
            'type'                    => 'select2_from_ajax',
            'entity'                  => 'service',
            'method'                  => 'post',
            'data_source'             => url('fetch/service'),
            'minimum_input_length'    => 0,
            // 动态传递status参数到后端接口
            'data' => [
                'status' => "function() { return $('select[name=status]').val(); }"
            ]
        ]
    ]);
}

2. 后端接收参数并过滤查询

修改fetchService方法中的查询逻辑,从请求中获取status参数,将其加入到查询条件里:

public function fetchService()
{
    return $this->fetch([
        'model'                 => Service::class,
        'searchable_attributes' => ['name'],
        'paginate'              => 10,
        'query'                 => function ($model) {
            $search = request()->input('q') ?? '';
            // 从请求中获取前端传递的status参数
            $statusParam = request()->input('status');
            
            // 初始化查询,仅当有status参数时添加过滤条件
            $query = $model->when($statusParam, fn($q) => $q->where('status', $statusParam));
            
            // 保留原有的名称搜索逻辑
            if ($search) {
                $query->where('name', 'like', "%$search%");
            }
            
            return $query;
        }
    ]);
}

内容的提问来源于stack exchange,提问作者KordDEM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 03:37:44