While I am testing out custom Auth guard with the following code, I got the error below.
> use IlluminateSupportFacadesAuth
> Auth::guard("my_custom_guard")
= IlluminateAuthRequestGuard {#5359}
> Auth::guard("my_custom_guard")->attempt([])
BadMethodCallException Method IlluminateAuthRequestGuard::attempt does not exist.
My config/auth.php
'defaults' => [
'guard' => 'api',
'passwords' => 'members',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'members',
],
'api' => [
'driver' => 'jwt',
'provider' => 'members',
],
'my_custom_guard' => [
'driver' => 'my_custom_driver',
],
],
I know that setting defaults
guard can solve this problem, as some previous answers suggested. However, I want to use any auth guard whenever necessary, that’s what custom guard is used for, isn’t it?
So other than updating defaults
value, are there any way to use custom guard?
Thank you very much in advance for your help.
Update 9/8/2024: forgot to put this up:
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Auth::viaRequest('custom-token', function (Request $request) {
// whatever auth way I want. Example below:
// return User::where('token', (string) $request->token)->first();
});
}
3
You have defined it (i.e. guards
) incorrectly. Also you need to defined it’s respective providers
that is missing in your code.
Do this changes in config/app.php
…
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'members',
],
'api' => [
'driver' => 'jwt',
'provider' => 'members',
],
'my_custom_guard' => [
'driver' => 'session', //you can change it accordingly
'provider' => 'custom_guard', //you need to map this with `providers` array
],
],
And then you also need to define your providers
array accordingly like this.
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => AppModelsUser::class,
],
'custom_guard' => [
'driver' => 'eloquent', //you can change it as well accordingly
'table' => AppModelsCustomGuard::class,
],
],
1