I'm trying to create an user token in laravel with passport, and when I try to call the service it gives me the data of the token and not the token.
Using the passport in the model of the user :
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
And controller for the login like
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Validator;
class UserController extends Controller
{
public $successStatus = 200;
public function login()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
return response()->json(['success' => $success], $this-> successStatus);
} else {
return response()->json(['error'=>'Unauthorised'], 401);
}
}
}
The response of the service is:
{
"success": {
"token": {
"name": "MyApp",
"abilities": [
"*"
],
"tokenable_id": 1,
"tokenable_type": "App\\Models\\User",
"updated_at": "2022-03-29T22:52:58.000000Z",
"created_at": "2022-03-29T22:52:58.000000Z",
"id": 2
}
}
}
Use:
'use Laravel\Passport\HasApiTokens'
Instead of
'use Laravel\Sanctum\HasApiTokens'