How to Use Token Authentication in Laravel: Simple Guide
In Laravel, use
Laravel Sanctum or Laravel Passport to implement token authentication. Sanctum is simpler for SPA and mobile apps, while Passport is for full OAuth2. You generate tokens for users and protect routes using auth:sanctum or auth:api middleware.Syntax
Token authentication in Laravel typically involves these parts:
- Token generation: Create a token for a user using
$user->createToken('token-name'). - Middleware protection: Use
auth:sanctumorauth:apimiddleware on routes to require valid tokens. - Token usage: Send the token in the
Authorizationheader asBearer {token}with API requests.
php
<?php // Generate token for authenticated user $token = $user->createToken('api-token')->plainTextToken; // Protect routes in routes/api.php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); });
Example
This example shows how to set up token authentication using Laravel Sanctum. It includes user login, token creation, and a protected route that returns user info only if the token is valid.
php
<?php // routes/api.php use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use App\Models\User; use Illuminate\Support\Facades\Route; // Login route to authenticate and create token Route::post('/login', function (Request $request) { $user = 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]); }); // Protected route Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); });
Output
{"token":"<generated_token_string>"}
// When calling /user with header Authorization: Bearer <generated_token_string>
// returns user data as JSON
Common Pitfalls
Common mistakes when using token authentication in Laravel include:
- Not installing or configuring
laravel/sanctumorlaravel/passportproperly. - Forgetting to add
HasApiTokenstrait to the User model. - Not setting the
Authorizationheader correctly withBearer {token}. - Using web middleware instead of API middleware for token routes.
- Not running migrations for Sanctum tables.
Example of a wrong and right way to protect routes:
php
// Wrong: Missing middleware or wrong middleware Route::get('/user', function () { return auth()->user(); }); // Right: Use auth:sanctum middleware Route::middleware('auth:sanctum')->get('/user', function () { return auth()->user(); });
Quick Reference
Summary tips for Laravel token authentication:
- Install Sanctum:
composer require laravel/sanctumand run migrations. - Add
HasApiTokenstrait to User model. - Generate tokens with
$user->createToken('name'). - Protect API routes with
auth:sanctummiddleware. - Send token in
Authorization: Bearer {token}header.
Key Takeaways
Use Laravel Sanctum for simple token authentication in APIs and SPAs.
Always protect routes with the correct middleware like auth:sanctum.
Generate tokens via the createToken method on the User model.
Send tokens in the Authorization header as Bearer tokens.
Ensure Sanctum is installed, configured, and migrations are run.