Redirect to Login page if ther user not logged in Laravel

8.5k Views Asked by At

I am using Laravel version 5. I have a route file for my project which contains plenty of lines. I need to put authentication like Redirect to login page if the user is not logged in. And I also want to prevent direct URL access if the user not logged in. What can I do?

And I have used below code

Route::group(array('before' => 'auth'), function(){
    Route::get('/', 'HomeController@index');
});

But this prevents only for home page. I need to protect All my routes. And also suggest me how to reduce route file lines.

1

There are 1 best solutions below

5
On BEST ANSWER

You can put as many routes in a Group as you like to

Route::group(array('before' => 'auth'), function(){
    Route::get('/', 'HomeController@index');
    Route::post('store', 'HomeController@store');
    Route::get('show', 'AnotherController@index');
    // ...
});

If you really need to protect all your routes, you could add

 public function __construct()
 {
      $this->middleware('auth');
 }

To your main controller class, Http/Controllers/Controller

Edit for your comment, taken from the docs, you may use

return redirect()->intended('view');

/**
 * Handle an authentication attempt.
 *
 * @return Response
 */
    public function authenticate()
    {
        if (Auth::attempt(['email' => $email, 'password' => $password]))
        {
            return redirect()->intended('dashboard');
        }
    }

}