Bird
Raised Fist0
Laravelframework~20 mins

Token management in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
Token Mastery in Laravel
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Laravel Sanctum token creation code?
Consider the following Laravel code snippet that creates a token for a user. What will be the output of return $token;?
Laravel
<?php
$user = App\Models\User::find(1);
$token = $user->createToken('api-token')->plainTextToken;
return $token;
AA string representing the plain text token, e.g., '1|randomcharacters...'
BAn object containing token details including expiration
CA boolean true indicating token creation success
DNull, because the token is not returned by default
Attempts:
2 left
💡 Hint
Remember that createToken returns a NewAccessToken object, and plainTextToken is a string.
❓ state_output
intermediate
2:00remaining
What is the value of $user->tokens()->count() after revoking tokens?
Given a user with 3 active tokens, what will be the count after running this code?
$user->tokens()->delete();
Laravel
<?php
$user = App\Models\User::find(1);
// Assume user has 3 tokens
$user->tokens()->delete();
$count = $user->tokens()->count();
return $count;
Anull
B3
C0
DThrows an exception
Attempts:
2 left
💡 Hint
Deleting tokens removes them from the database.
📝 Syntax
advanced
2:00remaining
Which option correctly revokes a specific token by its ID?
You want to revoke a token with ID 5 for a user. Which code snippet does this correctly?
A$user->tokens()->remove(5);
B$user->tokens()->find(5)->revoke();
C$user->tokens()->destroy(5);
D$user->tokens()->where('id', 5)->delete();
Attempts:
2 left
💡 Hint
Tokens are Eloquent models; deleting by query is common.
🔧 Debug
advanced
2:00remaining
Why does this token authentication fail in Laravel Sanctum?
Given this middleware code, why does token authentication fail?
public function handle($request, Closure $next) {
  if (! $request->user()) {
    return response()->json(['error' => 'Unauthenticated'], 401);
  }
  return $next($request);
}
AThe user model does not implement HasApiTokens trait
BThe token is not sent in the Authorization header as Bearer token
CThe middleware does not call <code>auth()->check()</code>
DThe middleware should return <code>$next($request->user())</code> instead
Attempts:
2 left
💡 Hint
Check how Sanctum expects tokens to be sent in requests.
🧠 Conceptual
expert
3:00remaining
Which statement about Laravel Sanctum token abilities is true?
Consider token abilities (scopes) in Laravel Sanctum. Which option correctly describes their behavior?
AAbilities restrict what actions a token can perform; checking abilities is done via <code>$request->user()->tokenCan('ability')</code>
BAbilities automatically expire tokens after 24 hours
CAbilities are stored encrypted and cannot be read by the application
DAbilities are only used for SPA authentication, not API tokens
Attempts:
2 left
💡 Hint
Think about how you limit token permissions in Laravel Sanctum.

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

  1. Step 1: Understand token management role

    Token management is about controlling access by issuing and verifying tokens.
  2. Step 2: Identify correct purpose in Laravel context

    Laravel uses tokens to securely authenticate users without exposing passwords.
  3. Final Answer:

    To control user access securely using secret tokens -> Option A
  4. 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?
easy
A. $user->makeToken()
B. $user->createToken('token-name')
C. $user->generatePassword()
D. $user->newApiKey()

Solution

  1. Step 1: Recall Laravel Sanctum token creation method

    Laravel Sanctum uses createToken() to generate tokens for users.
  2. Step 2: Match method names with Laravel documentation

    Only createToken() is the correct method; others are invalid or non-existent.
  3. Final Answer:

    $user->createToken('token-name') -> Option B
  4. Quick Check:

    Token creation method = createToken() [OK]
Hint: Remember: createToken() creates tokens in Laravel [OK]
Common Mistakes:
  • Using non-existent methods like makeToken()
  • Confusing token creation with password generation
  • Using wrong method names
3. Given this code snippet, what will return $user->tokens()->count(); output after creating two tokens?
$user = User::find(1);
$user->createToken('token1');
$user->createToken('token2');
return $user->tokens()->count();
medium
A. 2
B. 1
C. Error
D. 0

Solution

  1. Step 1: Understand token creation effect

    Each createToken() call adds one token record linked to the user.
  2. Step 2: Count tokens after two creations

    After two calls, the user has two tokens stored, so count() returns 2.
  3. Final Answer:

    2 -> Option A
  4. 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

  1. Step 1: Identify tokens property type

    $user->tokens returns a collection, not a query builder.
  2. Step 2: Understand collection vs query builder methods

    delete() is a query builder method; collections need each() or query to delete.
  3. Final Answer:

    tokens is a collection, so delete() cannot be called directly -> Option D
  4. 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

  1. Step 1: Understand token revocation requirements

    We want to delete all tokens except the current one, so we filter by token ID.
  2. Step 2: Use query builder to delete filtered tokens

    Using where('id', '!=', $currentTokenId) excludes current token, then delete() removes others.
  3. 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.
  4. Final Answer:

    $user->tokens()->where('id', '!=', $currentTokenId)->delete(); -> Option C
  5. 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