Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Token Management in Laravel
📖 Scenario: You are building a simple Laravel API that requires users to have tokens for authentication. You will create a token management system to store and check tokens.
🎯 Goal: Build a Laravel controller that manages user tokens by storing tokens in an array, setting a token expiration time, checking if a token is valid, and returning a response accordingly.
📋 What You'll Learn
Create an array to store tokens with user IDs
Add a configuration variable for token expiration time
Write a function to check if a token is valid based on expiration
Return a JSON response indicating token validity
💡 Why This Matters
🌍 Real World
Token management is essential for API authentication to control access securely.
💼 Career
Understanding token management helps backend developers build secure APIs and manage user sessions.
Progress0 / 4 steps
1
Create the token storage array
Create a protected array called $tokens inside a Laravel controller class called TokenController. The array should have these exact entries: 1 => 'abc123', 2 => 'def456', 3 => 'ghi789'.
Laravel
Hint
Define a protected property $tokens as an associative array inside the TokenController class.
2
Add token expiration configuration
Add a protected integer variable called $tokenExpiration inside the TokenController class and set it to 3600 (seconds).
Laravel
Hint
Define a protected integer property $tokenExpiration and assign it the value 3600.
3
Create a method to check token validity
Inside the TokenController class, create a public method called isTokenValid that accepts a string parameter $token. Use a foreach loop with variables $userId and $storedToken to iterate over $this->tokens. Return true if $token matches $storedToken, otherwise return false after the loop.
Laravel
Hint
Use a foreach loop to compare the input $token with each stored token. Return true if found, else false.
4
Add a method to respond with token validity
Add a public method called checkToken that accepts a Request $request. Retrieve the token from the request using $request->input('token'). Use $this->isTokenValid($token) to check validity. Return a JSON response with key 'valid' set to true or false accordingly.
Laravel
Hint
Get the token from the request, check validity using isTokenValid, then return a JSON response with the result.
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]