reans's avatar
Level 2

How to access test headers in RouteServiceProvider

I have a multi-tenant application where every object is scoped to a team. I want to bind each object based on its teamId for example:

Route::bind('item', function ($value) use ($teamId) {
              $item = Item::where('items.id', $value)
                  ->where('items.team_id', $teamId)
                  ->firstOrFail();

              if (!$item) {
                  abort(404);
              }

              return $item;
          });

When I send the request I am able to access a request team-id header in RouteServiceProvider like this:

 $request = app(Request::class);
 $teamId = $request->header('team-id');

This works fine, however the header is null when I set it in my tests. I am sending the header correctly because I can access it later in middleware - which runs after RouteServiceProvider.

Is there a way I can change my tests to get these headers earlier in the "request" lifecycle?

0 likes
2 replies
martinbean's avatar
Level 80

@reans You should use middleware instead.

You don’t want to be trying to access request-related data in service providers because those service providers are invoked for every request, include non-HTTP requests.

1 like

Please or to participate in this conversation.