Laravel Backpack 后台管理实现链接参数过滤

更新日期: 2019-05-08 阅读次数: 5365 字数: 307 分类: backpack

例如,默认 Backpack 实现的一个 CRUD controller 可以查看一个数据表中的所有数据,这里假设是所有的支付历史。

但是,我现在需要能够从用户列表页面通过一个链接,链接到支付历史页面时,可以只查看该用户的支付历史。

实现方法

route/admin.php 中添加两个路由

CRUD::resource('pay_history', 'PayHistoryCrudController');
CRUD::resource('user/{user_id}/pay_history', 'PayHistoryCrudController');

这样

  • 访问 /admin/pay_history 时,看到的就是所有的支付历史。
  • 访问 /admin/user/1/pay_history 时,看到的就是 user_id 为 1 的用户的个人支付历史。

Admin/PayHistoryCrudController.php 中进行修改

class PayHistoryCrudController extends CrudController
{
    public $user;

    public function __construct(Request $request)
    {
        $this->user = User::find($request->route('user_id'));
        parent::__construct();
    }

    public function setup()
    {
        $this->crud->setModel('App\Models\PayHistory');

        if ($this->user) {
            $this->crud->setRoute(
                config('backpack.base.route_prefix') . '/user/' . $this->user->id . '/pay_history'
            );
            $this->crud->setEntityNameStrings('支付历史', '支付历史 - ' . $this->user->name);
        } else {
            $this->crud->setRoute(config('backpack.base.route_prefix') . '/pay_history');
            $this->crud->setEntityNameStrings('支付历史', '支付历史');
        }

        if ($this->user) {
            $this->crud->addClause('where', 'user_id', '=', $this->user->id);
        }

    ...

}

404 的问题

旧版本的 backpack 会出现 404 的问题

参考这里的解决方案:https://github.com/Laravel-Backpack/CRUD/issues/252

trait 真是个神器。方便给多个 class 插入相同的函数功能列表。

reference variable name xxx more than once

Route pattern "/admin/xxx/{location}/location/{location}" cannot reference variable name "location" more than once

参考:Route pattern cannot reference variable name more than once

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式