Ad

Use A Model's Function In A Middleware?

- 1 answer

I'm using Laravel 5.1 and am creating a "Admin" middleware to check that a user has right to access a specific page.

I would like to do this, but it doesn't work:

public function handle($request, Closure $next)
{
    if ($this->auth->guest() or !$this->auth->user()->isAdmin())
        return redirect()->guest('auth/signin');

    return $next($request);
}

So I achieve my goal like this, but it seems weird:

public function handle($request, Closure $next)
{
    if ($this->auth->guest() or ! User::find($this->auth->user()->id)->isAdmin())
        return redirect()->guest('auth/signin');

    return $next($request);
}

Any suggestion? Am I missing something?

Ad

Answer

OKay, thank you for your help:

I had two User class (one in App\User and one ine App\Models\User). I changed my configuration in config/auth.php to set the model to App\Models\User::class and deleted the default User model present when installing Laravel. So now the isAdmin() function works.

And as xAoc told me, the code is now the following:

public function handle($request, Closure $next)
{
    if (!$this->auth->user()->isAdmin())
        return redirect()->guest('auth/signin');

    return $next($request);
}
Ad
source: stackoverflow.com
Ad