Jeffrey in his videos puts in the web.php all the routes, even routes from Ajax requests, and then he used to get the authenticated user from sessions using auth()->user()
In case that I want to put the Ajax requests in api.php should I use the api middleware for stateless requests and then token based authentication to access the authenticated user Or I can use the web middleware even in api.php ?
You cannot use the authenticated user from the session in api.php because by default it doesn't have the web middleware group. The idea is normally that all session/state related routes are defined in web.php. All stateless routes are registered in api.php and can have a different authentication method. For example an access token.
You can of course add all the needed middleware to the api group or connect the web middleware group to the api routes file in your RouteServiceProvider. Whatever works for you ;)
To get a better understanding, let's say that i have a multi page application and in some parts of it i use ajax requests to communicate with the server. Does it make sense to use the web middleware for both ajax and non-ajax requests ? I'm trying to understand why did Jeffrey put even the ajax requests through the web middleware. Is it more complex if you use api middleware for the ajax requests, with regards to authentication and authorization ?
Well, the user is already logged in and you already have the session available. It's perfectly fine to then reuse that session for the requests. Jeffrey calls them API calls because they return JSON, but they are not different than any other request to the server.It returns JSON instead of HTML.
If you decide to make your API publicly available it makes sense to have a stateless authentication method. But if you don't need that, defining them in the web routes is fine.
It's not more complex to use authentication for your API routes, but it is extra work to set up. You also need to have an API-token per user and make sure this token is available in the frontend. If you don't really need that extra stuff, keeping it simple is always the best solution ;)
Therefore if I understand correctly, the use cases for the api middleware are either when you have an SPA or if you have a public api that anyone can access