0

We have a large website with many pages. Almost all of them require the user to log in. Instead of specifying "Auth" on every single page, or on every single controller, I would like to set the routes based on if the user is logged in, like this:

// in web.php
if (Auth::isLoggedIn()) {
    Route::get('/', function () { return view('pages/dashboard'); });
    ... lots more
}

The reason I can't do this is because Auth uses sessions, and sessions are not yet initialized in web.php, since it is done as middleware which is not run yet at this point.

I'm using Laravel 8, I believe.

Thanks.

0

2 Answers 2

2

you can group the route that need the user to be logged in, then use auth middleware for the grouped routes:

Route::middleware(['auth'])->group(function () {
    Route::get('/', function () {
        //
    });

    Route::get('/', function () { return view('pages/dashboard'); });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! Thanks!
As an additional comment, you can customize the 403/forbidden route/page to redirect to different pages depending the original request.
0

Try using Laravel's Route middleware. Route middleware can be used to only allow authenticated users to access a given route.

1 Comment

No. If you check the other answer, it explain better how to bulk (using group).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.