Laravel Auth User API architecture problem

Viewed 65

I ran into a "good practice question" when was trying to wrote an API for an authenticated user.

So, if I'm not writing an SPA, then i need an API for making axios(for example) request to get authenticated user's data. And i got kinda stuck.

If I'll put all user data routes in web.php, then my controller will be forced to return JSON for Vue to parse the data, which is not really a good practice for web.php routes.

If I'll put all user data routes in api.php, then it's a good practice to return JSON from it's controllers, but i won't be able to get an authenticated user simply with auth()->user() because api.php doesn't use an authenticated user session. So I'm forced to put a damn sanctum token for each of api request, which is a little:

  1. annoying
  2. not possible when rendering full page with vue
  3. might be considered bad practice
  4. can be avoided by simply putting all routes to web.php

So, what is your opinion on where to put that kind of routes?

1 Answers

If the request you want to make is coming from a session-based authenticated user (you are authenticating your users using regular laravel sessions), then use the web.php file. If it is coming from an API-based authenticated user (you are authenticating your users using API tokens), then use api.php file.

It doesn't matter if the data that is going to be returned is JSON data or a blade view, if you are using regular session-based authentication, just use web.php file.

I assume you are not writing an API and you want to get the user data from a session-based authenticated user. In this case, you should definitely use web.php file for this and it is not a bad practice.

Related