Laravel use auth()->user() for api

Patrick Schocke picture Patrick Schocke · Nov 2, 2018 · Viewed 7.6k times · Source

I have a lot of functions that perform actions based of the permissions of the user. For the web, everything works fine. But I am slowly changing to more ajax and less reloading the page. However, I am not able to use my functions in my api controllers because I perform the check for the permission with

auth()->user()->...

Is there a change to use this also for my api controller? I know that I can acess the user model with $request->user, but if this is the only chance, I think I have to copy all my functions, one for web and one for api. Is there any other change to rewrite my functions that they can be performed form both, web and api controller?

Answer

John Halsey picture John Halsey · Nov 2, 2018

I think as long as you still use the 'auth:api' middleware on your api routes, you should be able to use the auth()->user() helper.

UPDATE

The auth:api middleware comes with Laravel Passport if you're using that (which I recommend).

https://laravel.com/docs/5.7/passport#protecting-routes