Table Of Contents
Problem
You need to extract the Bearer token from the Authorization header to authenticate API requests or perform custom token validation.
Solution
Use Laravel's built-in bearerToken()
method:
// In a controller or middleware
public function someMethod(Request $request)
{
$token = $request->bearerToken();
if (!$token) {
return response()->json(['error' => 'Token not provided'], 401);
}
// Use the token
// $token contains the token string without "Bearer " prefix
}
Alternative methods:
// Method 1: Using header() method
$authHeader = $request->header('Authorization');
$token = null;
if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
$token = substr($authHeader, 7);
}
// Method 2: In middleware
public function handle($request, Closure $next)
{
$token = $request->bearerToken();
// Validate token manually
$user = User::where('api_token', hash('sha256', $token))->first();
if (!$user) {
return response()->json(['message' => 'Unauthorized'], 401);
}
auth()->login($user);
return $next($request);
}
// Method 3: With Sanctum
if ($request->user('sanctum')) {
$token = $request->user()->currentAccessToken()->token;
}
Why It Works
The bearerToken()
method automatically extracts tokens from the Authorization: Bearer {token}
header format. It handles the parsing and returns just the token value, removing the "Bearer " prefix. This is the standard format for API authentication tokens.
For custom implementations or when you need the raw header:
// Get raw authorization header
$fullHeader = $request->header('Authorization'); // "Bearer your-token-here"
// Check if token exists in different formats
$token = $request->bearerToken()
?? $request->query('api_token')
?? $request->input('api_token');
Related: Laravel Collections: Beyond Basic Array Operations | Laravel Events and Listeners: Building Decoupled Applications | Building Multi-tenant Applications with Laravel: A Comprehensive Guide | Laravel Sanctum: API Token Authentication Made Simple | API Authentication & Security 2025: Complete Guide
Add Comment
No comments yet. Be the first to comment!