【问题标题】:Can't use Eloquent inside Slim Middleware不能在 Slim 中间件中使用 Eloquent
【发布时间】:2017-05-08 11:53:17
【问题描述】:

我正在使用 slim 框架,我只是想从我的中间件内部的数据库中检查一个值,但我收到了一个错误:

Message: Call to a member function connection() on null

这是我的中间件代码:

->add(function ($request, $response, $next) {

    $user = App\User::find($_SESSION['userid']);

    if($user->permission == 1  ){
        $response = $next($request, $response);
    }else{
        return $response->withRedirect('noPermission');
    }

    return $response;
});

我要把这个添加到我的组中

这就是我在 dependencies.php 文件中初始化 eloquent 的方式:

  $container['db'] = function ($container) {
    $capsule = new \Illuminate\Database\Capsule\Manager;
    $capsule->addConnection($container['settings']['db']);
    $capsule->setAsGlobal();
    $capsule->bootEloquent();
    return $capsule;
  };

这可能是在建立数据库连接之前执行的代码!?

感谢您的帮助

注意:我可以在路由中使用 eloquent

【问题讨论】:

  • 在哪里初始化eloquent?
  • 在 dependencies.php 文件中
  • 我们能看到那个文件吗?
  • 我在问题描述中添加了代码
  • 谢谢大家我解决了

标签: php eloquent slim


【解决方案1】:

容器可能还没有初始化 eloquent 的胶囊。你可以自己做。

$container->get('db');

将其添加到容器后执行此操作。

【讨论】:

    【解决方案2】:

    我刚刚通过编辑这样的依赖文件解决了这个问题:

        $capsule = new \Illuminate\Database\Capsule\Manager;
    $capsule->addConnection($container['settings']['db']);
    $capsule->setAsGlobal();
    $capsule->bootEloquent();
    $container['db'] = function ($container) {
        global $capsule;
        return $capsule;
    };
    

    【讨论】:

      【解决方案3】:

      在中间件中试试这个,但你必须先将中间件添加到应用程序中。

      $this->容器->db

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-08
        • 2017-02-18
        • 2017-03-14
        • 2017-06-06
        • 2016-11-10
        • 2016-01-08
        • 2022-08-03
        相关资源
        最近更新 更多