return $token;?<?php $user = App\Models\User::find(1); $token = $user->createToken('api-token')->plainTextToken; return $token;
createToken returns a NewAccessToken object, and plainTextToken is a string.The createToken method returns a Laravel\Sanctum\NewAccessToken object. Accessing plainTextToken property returns the token string that can be used for authentication.
$user->tokens()->delete();
<?php $user = App\Models\User::find(1); // Assume user has 3 tokens $user->tokens()->delete(); $count = $user->tokens()->count(); return $count;
Calling tokens()->delete() deletes all token records for the user. Therefore, counting tokens after deletion returns 0.
The tokens() relationship returns a query builder. Using where('id', 5)->delete() deletes the token with ID 5. The other methods either don't exist or cause errors.
public function handle($request, Closure $next) {
if (! $request->user()) {
return response()->json(['error' => 'Unauthenticated'], 401);
}
return $next($request);
}Laravel Sanctum expects the token to be sent in the Authorization header as a Bearer token. If the token is missing or malformed, $request->user() returns null, causing authentication failure.
Abilities (or scopes) define what a token is allowed to do. You check them in your code with tokenCan(). They do not control expiration or encryption, and they apply to API tokens as well as SPA tokens.