Token management helps keep users logged in safely. It controls who can use your app by giving and checking secret keys called tokens.
When you want users to log in once and stay logged in securely.
When building APIs that need to check if requests come from real users.
When you want to allow users to log out and stop using their tokens.
When you want to limit how long a user can use a token before it expires.
Syntax
Laravel
<?php
// Create a token for a user
$token = $user->createToken('token-name')->plainTextToken;
// Revoke tokens
$user->tokens()->delete();
Use createToken to make a new token for a user.
Use tokens()->delete() to remove all tokens for logout or security.
Examples
This makes a new token called 'mobile-app' for the user.
Laravel
<?php
// Create a token named 'mobile-app'
$token = $user->createToken('mobile-app')->plainTextToken;
This logs the user out from all devices by deleting tokens.
Laravel
<?php
// Delete all tokens for the user
$user->tokens()->delete();
Laravel automatically checks tokens in requests to protect routes.
Laravel
<?php
// Check token in middleware
if ($request->user()) {
// User is authenticated
}
Sample Program
This example shows a simple login route that creates a token, a protected route that returns user info if token is valid, and a logout route that deletes tokens.
Laravel
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
Route::post('/login', function (Request $request) {
$user = App\Models\User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
return response()->json(['message' => 'Invalid credentials'], 401);
}
$token = $user->createToken('api-token')->plainTextToken;
return response()->json(['token' => $token]);
});
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::middleware('auth:sanctum')->post('/logout', function (Request $request) {
$request->user()->tokens()->delete();
return response()->json(['message' => 'Logged out']);
});
OutputSuccess
Important Notes
Tokens should be kept secret like passwords.
Use HTTPS to protect tokens during transfer.
Laravel Sanctum is a simple way to manage tokens in Laravel apps.
Summary
Token management controls user access with secret keys.
Create tokens when users log in and delete them to log out.
Use Laravel Sanctum for easy and secure token handling.
Practice
(1/5)
1. What is the main purpose of token management in Laravel?
easy
A. To control user access securely using secret tokens
B. To store user passwords in plain text
C. To speed up database queries
D. To create user interface components
Solution
Step 1: Understand token management role
Token management is about controlling access by issuing and verifying tokens.
Step 2: Identify correct purpose in Laravel context
Laravel uses tokens to securely authenticate users without exposing passwords.
Final Answer:
To control user access securely using secret tokens -> Option A
Quick Check:
Token management = secure user access [OK]
Hint: Tokens control access, not UI or passwords [OK]
Common Mistakes:
Confusing tokens with passwords
Thinking tokens speed up queries
Mixing token use with UI design
2. Which Laravel method is used to create a new API token for a user?
Each createToken() call adds one token record linked to the user.
Step 2: Count tokens after two creations
After two calls, the user has two tokens stored, so count() returns 2.
Final Answer:
2 -> Option A
Quick Check:
Two tokens created = count 2 [OK]
Hint: Count tokens after creation equals number created [OK]
Common Mistakes:
Assuming tokens() returns zero without refresh
Thinking createToken() replaces old tokens
Expecting an error due to missing save
4. What is wrong with this code snippet for deleting a user's tokens?
$user = User::find(1);
$user->tokens->delete();
medium
A. User::find(1) returns null, causing error
B. delete() method does not exist in Laravel
C. tokens relationship does not exist by default
D. tokens is a collection, so delete() cannot be called directly
Solution
Step 1: Identify tokens property type
$user->tokens returns a collection, not a query builder.
Step 2: Understand collection vs query builder methods
delete() is a query builder method; collections need each() or query to delete.
Final Answer:
tokens is a collection, so delete() cannot be called directly -> Option D
Quick Check:
Collection.delete() invalid, use query builder [OK]
Hint: Use query builder for delete, not collection [OK]
Common Mistakes:
Calling delete() on collection directly
Not checking if user exists
Assuming delete() is a collection method
5. How can you revoke all tokens for the currently authenticated user except the current token in Laravel Sanctum?
hard
A. $user->currentAccessToken()->delete();
B. $user->tokens()->delete();
C. $user->tokens()->where('id', '!=', $currentTokenId)->delete();
D. $user->revokeTokensExceptCurrent();
Solution
Step 1: Understand token revocation requirements
We want to delete all tokens except the current one, so we filter by token ID.
Step 2: Use query builder to delete filtered tokens
Using where('id', '!=', $currentTokenId) excludes current token, then delete() removes others.
Step 3: Check other options for correctness
$user->tokens()->delete(); deletes all tokens including current; $user->currentAccessToken()->delete(); deletes only current; $user->revokeTokensExceptCurrent(); is not a Laravel method.
Final Answer:
$user->tokens()->where('id', '!=', $currentTokenId)->delete(); -> Option C
Quick Check:
Filter tokens by ID, then delete others [OK]
Hint: Filter tokens by ID to exclude current, then delete [OK]
Common Mistakes:
Deleting all tokens including current
Trying to call non-existent methods
Deleting only current token instead of others
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.