Laravel: How to Get Token from Request in API
When building secure APIs with Laravel, managing and retrieving authentication tokens correctly is essential. Whether you’re using Laravel Passport, Sanctum, or a custom JWT setup, knowing how to get token from request ensures your API endpoints remain safe and functional.
In this guide, you’ll learn practical methods to get token from request in Laravel, handle bearer tokens, and use them securely in authentication workflows. This article is written for both beginners and experienced Laravel developers who want to improve their API handling skills.
Understanding Laravel Token Authentication
Before diving into code, it’s important to understand what a token represents in Laravel APIs. A token acts as a unique key that verifies the identity of a user or client making a request. Instead of using sessions or cookies (as in web apps), tokens provide stateless authentication — perfect for RESTful APIs.
Laravel supports multiple authentication systems:
- Laravel Passport for OAuth2-based APIs.
- Laravel Sanctum for single-page apps and mobile APIs.
- JWT (JSON Web Tokens) using community packages.
Each of these stores and verifies tokens differently, but the method to extract a token from an incoming request remains similar.
How to Get Token from Request in Laravel
The simplest way to retrieve a token is from the request header, where it’s usually passed as a Bearer Token. Laravel provides several helper methods to make this easy.
Getting Token Using bearerToken()
Laravel’s Request object has a built-in method called bearerToken(). It extracts the token from the Authorization header automatically.
public function getUserToken(Request $request)
{
$token = $request->bearerToken();
return response()->json(['token' => $token]);
}
This method works perfectly when a client sends a request like:
Authorization: Bearer your_token_here
It’s a clean and secure way to get token from request in Laravel without manually parsing headers.
Getting Token from Headers Manually
In some cases, you may want to manually access headers. For instance, when tokens are not prefixed with “Bearer.”
public function getToken(Request $request)
{
$token = $request->header('Authorization');
return response()->json(['token' => $token]);
}
This method simply reads the header, which you can then process further.
If your token doesn’t include the “Bearer” keyword, you can clean it up manually:
$token = str_replace('Bearer ', '', $request->header('Authorization'));
Getting Token from Query or Form Data
Sometimes, tokens are passed through query strings or POST data, especially in older systems. You can still retrieve them safely.
$token = $request->input('token');
This retrieves the token from the request body or URL, such as:
GET /api/user?token=12345
However, this method is not recommended for secure APIs, as query strings can be logged or exposed.
Using Token with Laravel Middleware
Once you know how to extract a token, the next step is using it in middleware for authentication. Middleware allows you to automatically check tokens before processing the request.
Here’s a simple example:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckApiToken
{
public function handle(Request $request, Closure $next)
{
$token = $request->bearerToken();
if ($token !== config('app.api_token')) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $next($request);
}
}
Register the middleware in Kernel.php, and your routes will be automatically protected.
Handling Tokens in Laravel Sanctum
If you’re using Laravel Sanctum, getting a token from the request becomes even easier. Sanctum automatically verifies the token and authenticates the user.
Example:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
In this case, you don’t need to manually get the token — Laravel handles it through the middleware. But understanding how it works behind the scenes helps when debugging authentication issues.
Debugging Token Issues in Laravel
Sometimes, you might face problems where the API returns “Unauthenticated.” Here are common causes and fixes:
Token Not Found
Check if your client sends the token in the correct header format. It should look like:
Authorization: Bearer your_token_here
Token Expired
If you’re using JWT or Passport, expired tokens will fail authentication. You may need to refresh the token.
Incorrect Middleware
Ensure that your routes use the correct guard or middleware. For example:
Route::middleware('auth:api')->get('/profile', function (Request $request) {
return $request->user();
});
Wrong Guard Configuration
In config/auth.php, make sure your guards are properly configured for API use.
'guards' => [
'api' => [
'driver' => 'sanctum',
'provider' => 'users',
],
],
Securing Your Laravel Token Authentication
Security is critical when handling tokens. Always follow these best practices:
- Use HTTPS to protect tokens during transmission.
- Store tokens securely on the client side (not in local storage).
- Set short token lifetimes and enable refresh tokens when possible.
- Rotate tokens regularly for enhanced protection.
- Validate tokens in every request before granting access.
These measures reduce the risk of unauthorized access or token theft.
Laravel Get Token from Request in API Example
Here’s a full example of a route and controller handling a token-secured API request.
Route (in api.php):
Route::get('/secure-data', [TokenController::class, 'handle'])->middleware('auth:api');
Controller (TokenController.php):
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TokenController extends Controller
{
public function handle(Request $request)
{
$token = $request->bearerToken();
if (!$token) {
return response()->json(['error' => 'Token missing'], 401);
}
return response()->json([
'message' => 'Token received successfully',
'token' => $token,
]);
}
}
This approach combines best practices for security and efficiency.
Common Mistakes When Getting Token in Laravel
Developers often run into small but critical mistakes when working with tokens. Avoid the following pitfalls:
- Forgetting to include the
Authorizationheader. - Not using the
Bearerprefix. - Using session-based guards for APIs.
- Sending tokens in query strings.
- Not checking for expired tokens.
By following Laravel’s native methods and keeping security in mind, you can avoid these issues easily.
Frequently Asked Questions (FAQ)
How do I get the bearer token from a request in Laravel?
Use $request->bearerToken() to extract the token from the Authorization header safely.
Can I get the token without using middleware?
Yes. You can manually retrieve it using $request->header('Authorization'), but middleware is recommended for automation.
Why is my Laravel token not working?
Your token might be expired, missing the “Bearer” prefix, or sent using an incorrect guard. Check your API configuration and request headers.
How do I pass a token in Laravel API request?
Include it in the Authorization header like this: Authorization: Bearer your_token.
Is Laravel Sanctum better than Passport?
Sanctum is ideal for single-page and mobile apps due to its simplicity, while Passport is best for large, OAuth2-based systems.
Retrieving tokens from API requests in Laravel is straightforward once you understand the Request object and how headers work. Whether you use bearerToken() or access headers manually, Laravel provides the flexibility to handle authentication securely.
To master API authentication, keep your configurations consistent, always test with real clients, and prioritize security at every step.
Ready to build secure Laravel APIs? Start implementing token authentication in your next project and see how effortlessly Laravel handles it.



