Home > Software design >  Laravel: is there an easy way to force login?
Laravel: is there an easy way to force login?

Time:07-13

I want to implement user authentication (require login to visit any page) for a Laravel project (Laravel 7.x/8.x) that is currently open to any visitor without login. With Auth::routes() in web.php, every thing works as expected with respect to login process if a user accesses or is redirected to the login page.

Now I'm wondering if there's a straight forward and simple mechanism that will redirect a user to the login page if the user is not logged in when accessing any page of the project without having to modify the controller or view of each page. Specifically what I'm looking for is something that I can set in a config file, e.g. config/auth.php, say, 'force_login' => true/false, so if 'force_login' is set to true, the system would automatically check whether or not a user is logged in when the user access any page and redirect to the login page if the user is not logged in, and if 'force_login' is set to false, the system would bypass the authentication process all together. Such kind of mechanism may already exist, but I found no mention of it when I searched around online. I appreciate any suggestions/hints. Thanks.

CodePudding user response:

Yes, youu need to use the auth middleware on all the routes that you want to forced be logged, or tou could only group them in one.

// Auth is required to acces these routes
Route::middleware(['auth'])->group(function () {
    Route::get('/home', 'HomeController@index');
    Route::get('any_route', 'AnyController@index');
    ...
});

// Auth is not required
Route::get('/', function () {
    return view('welcome');
});
  • Related