Redirect to Login if user not logged in Laravel

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.


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.