简体   繁体   中英

Filter table with a column in Laravel Backpack

I have a Employee table which display like this:

+-------------------------------+
|  id  |    name    |   code    |
---------------------------------
|  1   | Employee 1 |    A1     |
|  2   | Employee 2 |    A2     |
| ...  |    ...     |   ...     |
+-------------------------------+

And I want to create a filter by code column in this table. My query will be like this:

SELECT name FROM employee WHERE code LIKE .% $filter %.

I searched in backpack document and trying to do like this

$this->crud->addFilter(
    [
        'type' => 'select2',
        'name' => 'code',
        'label' => 'Filter',
    ],
    function () {
        return Employee::select('code')->distinct()->get()->toArray();
    },
    function ($value) {
        $this->crud->addClause('where', 'code', $value);
    }
);

But it got error: htmlspecialchars() expects parameter 1 to be string, array given . How I can fix this?

Thank you very much!

Your code to generate the list of employee codes is returning an array like this at the moment, while the package is expecting an array of strings.

[
    ['code' => 'A1'],
    ['code' => 'A2'],
];

To fix the issue, you need to pluck the code column from the array, and key it by the code:

$this->crud->addFilter([
        'type' => 'select2',
        'name' => 'code',
        'label' => 'Filter',
    ],
    function() {
        return Employee::select('code')->distinct()->get()->pluck('code', 'code')->toArray();
    },
    function($value) {
        $this->crud->addClause('where', 'code', $value);
    });

This will result in something like:

[
    'A1' => 'A1',
    'A2' => 'A2',
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM