Php – How to redirect an unauthorized user to the login page in Laravel

laravellaravel-3PHP

I'm new to Laravel ( version 3 ), i do not know how to set Route and filters in Laravel so that any unauthorized user that is trying to access any url redirects to the login page (NOT the 404 error), in another word the default home page for unauthorized users is going to be the login page and for the authorized users it's going to be the dashboard.

Best Answer

If you are using laravel Auth class you can create an authorized route group. All routes that are defined there will be redirected if the user isn't logged in. Your router file will look something like this:

Route::get('/', array('as' => 'intro', 'uses' => 'intro@index'));
Route::get( 'login', array('as' => 'login', 'uses' => 'user@login'));
Route::get( 'logout', array('as' => 'logout', 'uses' => 'user@logout'));

// PROTECTED
Route::group(array('before' => 'auth'), function()
{
   Route::get('dashboard', array('as' => 'dashboard', 'uses' => 'user@dashboard'));
});

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