I’m trying to add functionality similar to the user resolver in Laravel’s Request class.
I have a SaaS application. I’ve created a middleware class to look at the request host and fetch the corresponding account based on the domain. It looks like this:
public function handle($request, Closure $next)
{
$host = $request->getHost();
$domain = Domain::whereName($host)->firstOrFail();
return $next($request);
}
I’ve extended the Request class with one in my application, and updated the reference in public/index.php to use this new class. I’ve also added three new methods:
public function account()
{
return call_user_func($this->getAccountResolver());
}
public function getAccountResolver()
{
return $this->accountResolver ?: function () {};
}
public function setAccountResolver(Closure $callback)
{
$this->accountResolver = $callback;
return $this;
}
The idea is, I want to be able to get the account from the request the same way I can get the currently logged-in user:
$user = $request->user();
$account = $request->account(); // My new method
I had a look in the Laravel codebase and they seem to use rebinding to add the user resolver. From the AuthServiceProvider class:
$this->app->rebinding('request', function ($app, $request) {
$request->setUserResolver(function () use ($app) {
return $app['auth']->user();
});
});
So I replicated this in my middleware method:
$this->app->rebinding('request', function ($app, $request) use ($domain) {
$request->setAccountResolver(function () use ($app, $domain) {
return $domain->account; // Domain belongs to an Account
});
});
But this doesn’t seem to get triggered. If I run dd($request) in the middleware I can see the $accountResolver property is an instance of a Closure (my callback), but when I dd($request) after the middleware class (say a controller action), the $accountResolver method is back to being null.
How can I get my account resolver to persist after my middleware, so that I can call $request->account() and get an Account instance throughout my application?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire