Daolin
Daolin

Reputation: 634

Laravel 5: how should I implement Auth::admin() as Auth::guest()?

I would like to have administrator authorization. so I have new class in middleware

class Admin {

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

    if ( Auth::check() && Auth::user()->isAdmin() )
    {
        return $next($request);
    }

    Session::flash('message', 'You need to be an administrator to visit this page.');

    return redirect('/');

}

}

Then register it in Kernel.php by adding

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'admin' => \App\Http\Middleware\Admin::class, //added line
];

I also defined isAdmin() in my user model. It works when I do this in the route:

get('protected', ['middleware' => ['auth', 'admin'], function() {
    return "this page requires that you be logged in and an Admin";
}]);

But I want to use it like Auth::admin() as Auth::guest(), where should I implement this function? Do I need a abstract admin() in Guard.php first?

I can get around with Auth::user()->isAdmin(), but I still want to know the right way to do it.

Thanks.

Thanks.

Upvotes: 1

Views: 3572

Answers (1)

Burak Ozdemir
Burak Ozdemir

Reputation: 5332

First, you don't need to include both auth and admin middlewares in your route as you already check the authentication within your admin middleware.

get('protected', ['middleware' => ['admin'], function() {
    return "this page requires that you be logged in and an Admin";
}]);

For your question, first, you need to extend the \Illuminate\Auth\Guard and use it instead. Let's say you have a Extensions folder in your app folder.

namespace App\Extensions;

use Illuminate\Auth\Guard;

class CustomGuard extends Guard
{
    public function admin()
    {
        if ($this->user()->isAdmin()) {
            return true;
        }
        return false;
    }
}

Then in your AppService Provider,

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Auth\EloquentUserProvider;
use App\Extensions\CustomGuard;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {  
        Auth::extend('eloquent.admin', function ($app) {
            $model = $app['config']['auth.model'];
            $provider = new EloquentUserProvider($app['hash'], $model);
            return new CustomGuard($provider, \App::make('session.store'));
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Finally, in your config/auth.php file, change the line as below.

'driver' => 'eloquent.admin'

Then you should be fine.

Upvotes: 1

Related Questions