Ela Buwa
Ela Buwa

Reputation: 1704

Accessing model in middleware in laravel

I am building a multi tenant app and I am distinguishing the tenant based on the subdomain. I have registered a global middleware on the laravel kernel and I need to use my model in the middleware to get DB connection and then assign the values to a second mysql connection.

I tried doing what the documentation said but being a bit on laravel I am not getting my head around this.

Below is my middleware. Seems like a linking issue.

This is my middleware.

 <?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);
    }
}

Below is my model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

}

I get

"FatalErrorException in TenantIdentification.php line 28: Class 'Class 'App\Models\Tenant' not found".

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

My model is located in app\Models\Tenant.php Does the boot function do anything? If I can load the model there, how would I refer to it within the handle method?

Upvotes: 6

Views: 9528

Answers (2)

Ahmad Rezk
Ahmad Rezk

Reputation: 196

In the model file you were invoking the namespace with just App and you referenced it with App\Models.

Therefore, change the namespace in the model file to

namespace App\Models;

Upvotes: 2

kai ogita
kai ogita

Reputation: 136

in the model file how about replacing

namespace App;

with

namespace App\Models;

Upvotes: 1

Related Questions