Thursday, March 2, 2017

Laravel 5.3: Create Admin Middleware

I created a Middleware called Admin

public function handle($request, Closure $next)
{
    if (Auth::guard($guard)->check()) {
        if (Auth::user()->isAdmin())
            return redirect('/list_host');
        else {
            // return $next($request);
            return redirect('/home');
        }
    }
}

IsAdmin looks like this:

public function isAdmin()
{
    return $this->is_admin;
}

And their I want to check if the user is logged in and has admin-rights. I also added it to Kernel.php

protected $routeMiddleware = [
    'auth'       => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings'   => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can'        => \Illuminate\Auth\Middleware\Authorize::class,
    'guest'      => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle'   => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'admin'      => \App\Http\Auth\Middleware\Admin::class,
];

And then I use it in the Routes/web.php

Route::get('/list_hosts', function () {
    return view('/list_hosts');
})->middleware('admin');

Unfortunately also none Admins can view the Site. Any suggestions?



via AppleForTheKing

Advertisement