Leff
Leff

Reputation: 1320

Laravel - route model binding with request headers

I am wondering is it possible to do something similar to route model binding, but with request headers. I have a query that I check on my api endpoints, that looks like this:

User::where('telephone', $request->header('x-user'))->firstOrFail();

Is it possible to somehow avoid repeating this query in every method in controllers, but to apply it to routes, so that I could just get the user object just like in a route model binding with type hinting in a function, for every route that in an api routes folder:

public function userTransactions(User $user)
{
    //
}

Upvotes: 0

Views: 1112

Answers (1)

user320487
user320487

Reputation:

Create a middleware and assign it to the desired routes.

Option 1

In your middleware do:

$user = User::where('telephone', $request->header('x-user'))->firstOrFail();

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

You can then request()->get('user_model') anywhere in your controller

Option 2

Start by creating a global scope class that conforms to your query. Here you'd get the header value and use that in the scope.

https://laravel.com/docs/5.5/eloquent#global-scopes

Next in the middleware, add the scope to the model using addGlobalScope

User::addGlobalScope(new HeaderScope())

Now all queries for User will have a where clause with your header value.

You can subsequently remove the scope or ignore global scopes if needed.

Upvotes: 0

Related Questions