Filter table with a column in Laravel Backpack

懵懂的女人 提交于 2021-01-27 12:20:45

问题


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!


回答1:


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',
];


来源:https://stackoverflow.com/questions/57121402/filter-table-with-a-column-in-laravel-backpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!