【问题标题】:Accessing model in middleware in laravel在 laravel 的中间件中访问模型
【发布时间】:2017-08-03 06:43:21
【问题描述】:

我正在构建一个多租户应用程序,并且我正在根据子域来区分租户。 我在 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);
    }
}

下面是我的模型。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

}

我明白了

“TenantIdentification.php 第 28 行中的 FatalErrorException:类 '找不到类'App\Models\Tenant'”。

第 28 行是$tenant = \App\Models\Tenant::where('tenantKey', $tk)-&gt;first();

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

【问题讨论】:

  • app\Models\Tenant.php 文件中的类名是否正确?请向我们展示此文件的内容
  • 上面已经提到了。该模型名为“租户”。
  • 对不起。将模型中的命名空间更改为 App\Models;
  • 哈哈,感觉就是这么小。它正在工作。

标签: php laravel laravel-5


【解决方案1】:

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

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

namespace App\Models;

【讨论】:

    【解决方案2】:

    在模型文件中如何替换

    namespace App;
    

    namespace App\Models;
    

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      相关资源
      最近更新 更多