0

I want to append an auth user object (if available) to all responses on my Laravel app.

I have the following code here as Auth User object

  "user": {
    "name": "mike",
    "has_active_subscription": false,
    "is_onboarded": false,
    "email_verified": false
  }

Is there a middleware approaching to attaching this to all responses?

0x0
  • 363
  • 1
  • 4
  • 19

2 Answers2

1

You can make middleware or use trait here. I am doing it with trait ,

namespace App\Traits;
            
use Illuminate\Http\Response;
            
    trait Response{
                
        protected function response($response) {
            //import auth above
            $user = Auth::user();
            if (isset($user)) {
                $response = [...$response, ...$user];
            }
        
        return response()->json($response);
    }
}

Now make a parent controller BaseController

class BaseController {
   use Response;
}

Now just extends your other controller with BaseController and you can use response() method easily in that controller too.
0

but I think this will help:

  1. An assumption - I believe you are saying that yes, this line will get you the user you want:

    $user = $team->User()->first();
    

and you merely want to bind it to the request so that you can access this user later in your app via:

   $request->user()
  1. If this is true, then all I did was simplify the code you provided to add:

    $request->merge(['user' => $user ]);
    

//add this

$request->setUserResolver(function () use ($user) {
    return $user;
});

// if you dump() you can now see the $request has it

dump($request->user());

return $next($request);

I also $request->user() in the route closure, and it is there.

The app rebinding was a little strange to me, and didn't seem necessary. I'm not sure that anything would really need this for what you are doing.

Also follow this Answer It will help you more.

Rakesh kumar Oad
  • 1,332
  • 1
  • 15
  • 24