3

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
  • do you still want the auth check to be done incase of API calls ? Commented Nov 2, 2018 at 18:11
  • It's worth mentioning that if auth()->user() doesn't work, $request->user() shouldn't work either. They're both made available by authentication middleware. Commented Nov 3, 2018 at 6:03

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.