在 Laravel 中间件中访问模型

Ela*_*uwa 6 php laravel laravel-5

我正在构建一个多租户应用程序,并且根据子域来区分租户。我已经在 laravel 内核上注册了一个全局中间件,我需要在中间件中使用我的模型来获取数据库连接,然后将值分配给第二个 mysql 连接。

我尝试按照文档中的说明进行操作,但由于对 laravel 有点了解,所以我无法理解这一点。

下面是我的中间件。似乎是一个链接问题。

这是我的中间件。

 <?php

namespace App\Http\Middleware;

use Closure;

class TenantIdentification
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function boot(Router $router)
    {
        parent::boot($router);

        $router->model('tenant', '\App\Models\Tenant');
    }

    public function handle($request, Closure $next)
    {

        $tk = "HYD"; //hardcoded for the time being

        $tenant = \App\Models\Tenant::where('tenantKey', $tk)->first();

        var_dump($tenant);
        exit();
        return $next($request);
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是我的模型。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tenant extends Model
{
    protected $table = 'tenantinfo';

}
Run Code Online (Sandbox Code Playgroud)

我明白了

“TenantIdentification.php 第 28 行出现 FatalErrorException:未找到类‘Class 'App\Models\Tenant'”。

28号线是$tenant = \App\Models\Tenant::where('tenantKey', $tk)->first();

我的模型位于 app\Models\Tenant.php 启动功能有什么作用吗?如果我可以在那里加载模型,我将如何在句柄方法中引用它?

Ahm*_*ezk 2

在模型文件中,您使用just App调用名称空间,并使用 引用它App\Models

因此,将模型文件中的命名空间更改为

namespace App\Models;
Run Code Online (Sandbox Code Playgroud)