Laravel - How to redirect to login if user is not authenticated Laravel - How to redirect to login if user is not authenticated laravel laravel

Laravel - How to redirect to login if user is not authenticated


The controller is not the right place to check if a user is authenticated or not. You should use a middleware for that. To get info on what a middleware is check here

Let's see how you can use the default Laravel's auth middleware for this purpose:

First of all get rid of your AdminBaseController and use only AdminController

Then you have to check that the auth middleware is enabled in the file app\Http\Kernel.php

You should have the line:

protected $routeMiddleware = [    'auth' => \App\Http\Middleware\Authenticate::class,

This means that the middleware is active and usable for your routes.

Now let's go inside the middleware class in app\Http\Middleware\Authenticate.php to specify the middleware's behaviour :

//this method will be triggered before your controller constructorpublic function handle($request, Closure $next){    //check here if the user is authenticated    if ( ! $this->auth->user() )    {        // here you should redirect to login     }    return $next($request);}

Now the only thing left to do is to decide for what routes you should apply the middleware. Let's suppose you have two routes that you want to be only accessible from authenticated users, you should specify to use the middleware for these two routes in this way:

Route::group( ['middleware' => 'auth' ], function(){    Route::get('admin/index', 'AdminController@index');    Route::get('admin/ajuda', 'AdminController@ajuda');});


Use middleware for this purpose and then in controller constructor use it as in example below.

public function __construct(){    $this->middleware('guest', ['except' => 'logout']);}

And then you need to secure routes where you want from user to be logged in to access.

Route::group(['middleware' => 'auth'], function() {      Route::get('/dashboard', 'DashboardController@index');});


In Laravel 5.5 , an unauthenticated user will cause the Authenticate middleware to throw a AuthenticationException exception.

protected function authenticate(array $guards){ if (empty($guards)) {  return $this->auth->authenticate(); } foreach ($guards as $guard) {  if ($this->auth->guard($guard)->check()) {      return $this->auth->shouldUse($guard);  } } throw new AuthenticationException('Unauthenticated.', $guards);}

This will be caught by the app/Exceptions/Handler class which will call its render method which is responsible for converting a given exception into a HTTP response.

public function render($request, Exception $exception){ return parent::render($request, $exception);}

App/Exceptions/Handler extends 'Illuminate\Foundation\Exceptions\Handler', located inside '/vendor/laravel/src/Illuminate/Foundation/Exceptions/Handler'. It has its own render method. Within that render method, there's a if else statement that says.

elseif ($e instanceof AuthenticationException){ return $this->unauthenticated($request, $e);}

Below is the ‘unauthenticated‘ method that is called by the above within the same class

protected function unauthenticated($request, AuthenticationException $exception){  return $request->expectsJson() ? response()->json(['message' => $exception->getMessage()], 401) : redirect()->guest(route('login'));}

within this method is where you redirect an unauthenticated user.

As far as I can see, this is what goes on behind the scenes.