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

Viewed 9604

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?

2 Answers

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

API and Web are different concepts and authentication has to handled differently.
As i understand you want to use the functions from web related controllers in the API section.
If you are using for internal purpose then you can have additional variable in your function not to check the authentication (assume that your function doesn't require user releated information to progress).
EG:

  function showRecord($api = false){
     if($api){
       //don't authenticate
    }else{
       //authenticate
    }

    //rest of the code here
}

Another way
Separate the common code to one function and call it in the api controller or web controller based on your requirement.
EG: (All three controller has to be in the same namespace or you have to use them properly if they are in different namespaces):

// Controller: CommonController
function myCommonfunction($var){
  //db query or any processing
}

//function from api controller
function doSomethingApi(){
   $ctrl = new CommonController();
   $res = $ctrl->myCommonfunction('test');
   return $res
}
//function from webcontroller
function doSomething(){
   $ctrl = new CommonController();
   $res = $ctrl->myCommonfunction('web');
}



So how you are going to approach is purely based on your application structure.

Related