Search code examples
phpauthenticationmiddlewarelaravel-5

Laravel 5.2: How to use auth in middleware


I've create a new middleware name Adminpanel

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class Adminpanel
{
    public function handle($request, Closure $next)
    {
        if(Auth::user()->role == 'admin'){
            return $next($request);
        }else{
            return redirect('admin/login');
        }
    }
}

and register middle ware

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'adminpanel' => \App\Http\Middleware\Adminpanel::class,
];

and route

Route::group(['middleware' => ['web','adminpanel']], function () {
Route::get('/admin/dashboard/', 'admin\Dashboard@index');
//

});

but when I run, It ask me Trying to get property of non-object, means I could not access Auth class here, can somebody tell me what is the mistake and how to access Auth Facade in middleware.

and this is my authentication code

public function authenticate(Request $request)
{
    if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'), 'role' => 'admin'], $request->input('remember'))) 
    {
        return redirect()->intended('admin/dashboard');
    }
    else{
        return redirect('admin')->with('response',-1);
    }
}

Thanks


Solution

  • It doesn't mean you couldn't access Auth class. It means, that user is not authenticated and Auth::user() returns NULL.

    Make sure that only authenticated users can access your route by using auth middleware for that route or first check if user is authenticated:

    if(Auth::check() && Auth::user()->role == 'admin'){
      return $next($request);
    } else {
      return redirect('admin/login');
    }