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.
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');
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.