I tried implementing Passport to my project and upon Login attempt, I cannot return the access token. This is my User model
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasFactory, Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
And this is the Login controller, the login works, if i try to just return the authenticated user it works, but createToken() method is not recognized for some reason
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class LoginController extends Controller
{
public function Login(Request $request){
$login = $request->validate([
'email' => 'required|string|max:255',
'password' => 'required|string|max:255',
]);
//Check wether the login credentials are valid
if( !Auth::attempt($login)){
return response(['message' => 'Invalid login credentials'], 401);
}
else{
return(Auth::user()->createToken());
}
}
}
And this is the config file for the auth.php, I added the api driver and provider as the documentation suggested
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
CodePudding user response:
The reason behind this is that you cannot pass any value to the access token. Do the below code :
$token = auth()->user()->createToken('API Token')->accessToken;
return response(['user' => auth()->user(), 'token' => $token]);
CodePudding user response:
Try out this.
public function Login(Request $request){
$login = $request->validate([
'email' => 'required|string|max:255',
'password' => 'required|string|max:255',
]);
//Check wether the login credentials are valid
if( !Auth::attempt($login)){
return response(['message' => 'Invalid login credentials'], 401);
}
else{
$token = Auth::user()->createToken('TutsForWeb')->accessToken
return $token;
}
}