Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to Login if user not logged in Laravel

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.

like image 926
rkaartikeyan Avatar asked Feb 06 '15 10:02

rkaartikeyan


People also ask

How to Redirect user to Login page if not logged in Laravel?

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

How do I redirect back to original URL after successful login in laravel?

Basically we need to set manually \Session::put('url. intended', \URL::full()); for redirect. That's what redirect()->guest('login') is for.

How can I tell if logged in laravel 8?

“check if user is logged in laravel 8” Code Answer'sif (Auth::check()) { // The user is logged in... }


Video Answer


2 Answers

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.

like image 131
lukasgeiter Avatar answered Sep 22 '22 03:09

lukasgeiter


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(){

    });
});
like image 28
pranavbapat Avatar answered Sep 20 '22 03:09

pranavbapat