Search code examples
phplaravelcrudlaravel-backpack

Filter the output of a select2_from_ajax field depending on another field in crud Backpack Laravel


I have two fields

public function setupCreateOperation()
{
    ...
    $this->crud->addFields([
        [
            'name'    => 'status',
            'label'   => trans($this->trans_prefix . 'status'),
            'type'    => 'select_from_array',
            'options' => [
                0 => 'one',
                1 => 'two'
            ],
        ],
        [
            '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,
        ]
    ]);
}

Can I somehow filter the output of the service_id field depending on the status parameter? Currently my search function looks like this

public function fetchService()
{
    return $this->fetch([
        'model'                 => Service::class,
        'searchable_attributes' => ['name'],
        'paginate'              => 10,
        'query'                 => function ($model) {
            $search = request()->input('q') ?? false;

            if ($search) {
                return $model->where('name', 'like', "%$search%");
            } else {
                return $model;
            }
        }
    ]);
}

It would be great to somehow pass the status parameter to the function fetchService(). Then the queries would look something like this

'query' => function ($model) {
    $search = request()->input('q') ?? false;
    
    $status_param = $this->crud('status'); // something like this

    if ($search) {
        return $model->where('name', 'like', "%$search%")->where('status', $status_param);
    } else {
        return $model->where('status', $status_param);
    }
}

Solution

  • If you add 'include_all_form_fields' => true you will receive the whole form in the controller.

    [
            '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,
            'include_all_form_fields' => true
        ]
    

    So in Fetch method check all the parameters: dd($request->all());

    Cheers.