Monday, March 13, 2017

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?



via Ela Buwa

Advertisement