Redirect to Login if user not logged in Laravel

59,555

Solution 1

Laravel 5.4

Use the built in auth middleware.

Route::group(['middleware' => ['auth']], function() {
    // your routes
});

For a single route:

Route::get('profile', function () {
    // Only authenticated users may enter...
})->middleware('auth');

Laravel docs

Laravel 4 (original answer)

That's already built in to laravel. See the auth filter in filters.php. Just add the before filter to your routes. Preferably use a group and wrap that around your protected routes:

Route::group(array('before' => 'auth'), function(){
    // your routes

    Route::get('/', 'HomeController@index');
});

Or for a single route:

Route::get('/', array('before' => 'auth', 'uses' => 'HomeController@index'));

To change the redirect URL or send messages along, simply edit the filter in filters.php to your liking.

Solution 2

To avoid code repetition, You can use it in middleware. If you are using the Laravel build in Auth, You can directly use the auth middleware as given,

Route::group(['middleware' => ['auth']], function() {
   // define your route, route groups here
});

or, for a single route,

Route::get('profile', function () {

})->middleware('auth');

If you are building your own, custom Authentication system. You should use the middleware which will check the user is authenticated or not. To create custom middleware, run php artisan make:middleware Middelware_Name_Here and register the newly created middleware.

Solution 3

It's absolutely correct what other people have replied. This solution is for Laravel 5.4 But just in case, if you have more than one middleware applying to routes, make sure 'auth' middleware comes in the end and not at the start.

Like this:

Route::prefix('/admin')->group(function () {
    Route::group(['middleware' => 'CheckUser', 'middleware' => 'auth'], function(){

    });
});
Share:
59,555
rkaartikeyan
Author by

rkaartikeyan

I am a Website Developer using Both PHP and ASP.

Updated on July 09, 2022

Comments

  • rkaartikeyan
    rkaartikeyan almost 2 years

    i am new to laravel,

    i have code in my controller's __construct like

    if(Auth::check())
    {
        return View::make('view_page');
    }
    
    return Redirect::route('login')->withInput()->with('errmessage', 'Please Login to access restricted area.');
    

    its working fine, but what i wants is. its really annoying to put these coding in each and every controller, so i wish to put this Verify Auth and redirect to login page in one place, may be in router.php or filters.php.

    I have read some posts in forum as well as in stackoverflow, and added code in filters.php like below but that's too not working.

    Route::filter('auth', function() {
        if (Auth::guest())
        return Redirect::guest('login');
    });
    

    Please help me to resolve this issue.