Home > Enterprise >  Same route, different page for authenticated user or not
Same route, different page for authenticated user or not

Time:09-21

I want to display either welcome.blade.php or login.blade.php with the same base url / (because the login is in the main page)

Is this a good convention to check it in the web.php:

Route::get('/'), function () {
    if (auth()->check()) {
        // return the welcome.blade.php view
    } else {
        // return the login.blade.php view
    }
}

Or I should do this in a different place?

CodePudding user response:

Separation of concern ! It means that whatever the module/method you write should be pure from side effects and has only one job.

web.php in routes directory serves all the routes file. So if you try to put the business logic here, it will still work but it will violate the standard of framework. All business logic either should go to controllers , helpers and all the authentication related stuff should go to middlewares. Therefor, we should handle this logic inside the controllers if it is specific to single route. In our case /. Otherwise if we have to handle generic authentication stuff, we should go into middleware.

Therefor, the flow would look something like this

  • User hit the route /
  • Through the web.php, it redirected to particular controller let say HomeController.
  • Inside the HomeController , you will put the same condition and render the view accordingly. i.e
if (auth()->check()) {
        // return the welcome.blade.php view
    } else {
        // return the login.blade.php view
}

We can achieve the same thing in web.php but it will not be according to the framework standard. Further, If you have to do more stuff other than just rendering view, it will get more complicated in web.php.

I hope it will answer your question.

Thanks,

  • Related