Created
October 29, 2020 12:57
-
-
Save blood72/887439a9e667e2c286eae1248dc13e29 to your computer and use it in GitHub Desktop.
Change Auth default guard dynamically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
class DefaultGuardChangeDynamically | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @param string $guard | |
* @param string|null $provider | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next, $guard, $provider = null) | |
{ | |
if ($guard !== 'sanctum') { | |
config()->set('sanctum.guard', $guard); // prevent infinite loop | |
} | |
auth()->setDefaultDriver($guard); | |
$this->setGuardProvider($provider); | |
return $next($request); | |
} | |
/** | |
* @param string|null $provider | |
*/ | |
protected function setGuardProvider($provider) | |
{ | |
if (is_not_null($provider)) { | |
foreach (config('auth.guards') as $key => $config) { | |
if (isset($config['provider'])) { | |
config()->set("auth.guards.$key.provider", $provider); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment