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.
if(Auth::check()) { return View::make('view_page'); } return Redirect::route('login')->withInput()->with('errmessage', 'Please Login to access restricted area. ');
Basically we need to set manually \Session::put('url. intended', \URL::full()); for redirect. That's what redirect()->guest('login') is for.
“check if user is logged in laravel 8” Code Answer'sif (Auth::check()) { // The user is logged in... }
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
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.
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(){
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With