In Laravel 9, I am trying to hit the login API with the custom guard client
, I am getting the following error. Please help.
BadMethodCallException: Method Laravel\Passport\Guards\TokenGuard::attempt does not exist.
config/Auth.php
'guards' => [
...
'client' => [
'driver' => 'passport',
'provider' => 'client',
],
],
'providers' => [
...
'client' => [
'driver' => 'eloquent',
'model' => App\Models\Client::class,
],
],
Error line: if(!$authGuard->attempt($login)){
api/AuthController.php
public function login(Request $request){
$login = $request->validate([
'email' => 'required|string',
'password' => 'required|string',
]);
try {
$authGuard = Auth::guard('client');
if(!$authGuard->attempt($login)){
$data = 'Invalid Login Credentials';
$code = 401;
} else {
$user = $authGuard->user();
$token = $user->createToken('user')->accessToken;
$code = 200;
$data = [
'user' => $user,
'token' => $token,
];
}
} catch (Exception $e) {
$data = ['error' => $e->getMessage()];
}
return response()->json($data, $code);
}
Models/Client.php
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class Client extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
CodePudding user response:
I think Auth::attempt()
is not compatible with passport.
So, you can use Auth::check()
method instead.
CodePudding user response:
I solved it by changing the driver from passport
to session
in config/auth.php
'clients' => [
'driver' => 'session',
'provider' => 'clients',
],
I am not sure this is the correct solution, but it works.
Please feel free to post the answer if there is any better solution
Thanks
CodePudding user response:
attempt() is only available to guards implementing the StatefulGuard interface.
So i agree with John that attempt is not compatible with Passport.
You can try this it should work :
auth()->guard('client')->setUser($login);
or Auth::guard('client')->setUser($login);