Discover how to protect your app's data without writing endless login checks!
Why API authentication with Sanctum in Laravel? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine building a web app where users must log in to access their private data, and you try to check their username and password manually on every API request.
Manually checking credentials on each request is slow, risky, and can expose sensitive data. It's easy to make mistakes that let unauthorized users in or lock out real users.
Sanctum handles API authentication securely and automatically by issuing tokens and verifying them behind the scenes, so you don't have to write complex login checks yourself.
if ($request->header('Authorization') === 'user-secret') { // allow access } else { // deny }
if (Auth::guard('sanctum')->check()) { // allow access } else { // deny }
It lets you protect your API easily and safely, so only logged-in users can access their data without extra hassle.
A mobile app where users log in once, then securely fetch their profile and settings without re-entering passwords every time.
Manual API checks are slow and unsafe.
Sanctum automates token-based authentication.
This keeps your app secure and user-friendly.
Practice
Solution
Step 1: Understand Sanctum's role
Sanctum is designed to provide a simple way to authenticate API requests using tokens.Step 2: Compare options
The incorrect options relate to frontend routing, database migrations, and SQL query optimization, which are other Laravel features, not Sanctum's main purpose.Final Answer:
To provide simple token-based API authentication -> Option BQuick Check:
Sanctum = API token authentication [OK]
- Confusing Sanctum with database or routing features
- Thinking Sanctum manages frontend or SQL optimization
Solution
Step 1: Identify Sanctum middleware syntax
Sanctum uses 'auth:sanctum' middleware to protect routes requiring token authentication.Step 2: Check each option
Route::middleware('auth:sanctum')->get('/user', function () { return auth()->user(); }); uses 'auth:sanctum' correctly; others use incorrect or incomplete middleware names.Final Answer:
Route::middleware('auth:sanctum')->get('/user', function () { return auth()->user(); }); -> Option AQuick Check:
Sanctum middleware = 'auth:sanctum' [OK]
- Using 'auth' instead of 'auth:sanctum'
- Omitting middleware or using wrong names like 'sanctum' alone
- Confusing 'api' middleware with Sanctum middleware
use Illuminate\Http\Request;
Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
return $request->user()->name;
});Solution
Step 1: Understand the middleware effect
The 'auth:sanctum' middleware ensures the request is authenticated and $request->user() returns the authenticated user model.Step 2: Analyze the return statement
The code returns $request->user()->name, which outputs the authenticated user's name.Final Answer:
The name of the authenticated user -> Option AQuick Check:
$request->user()->name = user name [OK]
- Assuming user() returns null or causes error
- Confusing user name with email
- Ignoring middleware authentication effect
use App\Models\User; $user = User::find(1); $token = $user->createToken; return $token->plainTextToken;
Solution
Step 1: Check method call syntax
The createToken method must be called with parentheses and a token name string, e.g. createToken('token-name').Step 2: Analyze given code
The code uses $user->createToken without parentheses, so it references the method, not calls it, causing an error.Final Answer:
Missing parentheses when calling createToken() method -> Option DQuick Check:
Method calls need parentheses () [OK]
- Forgetting parentheses on method calls
- Not passing token name string to createToken()
- Assuming plainTextToken is invalid
Solution
Step 1: Review createToken method signature
The createToken method accepts the token name as first argument and an array of scopes as second argument.Step 2: Evaluate each option
$token = $user->createToken('api-token', ['orders', 'products']); correctly passes the token name and scopes array. $token = $user->createToken('api-token')->scopes(['orders', 'products']); incorrectly chains scopes() which does not exist. $token = $user->createToken('api-token', 'orders', 'products'); passes scopes as separate arguments, which is invalid. $token = $user->createToken(['orders', 'products']); passes scopes as first argument without token name.Final Answer:
$token = $user->createToken('api-token', ['orders', 'products']); -> Option CQuick Check:
createToken(name, scopes array) = correct [OK]
- Passing scopes as separate arguments instead of array
- Trying to chain scopes() method
- Omitting token name argument
