When building secure APIs in Laravel, you often need to ensure that users are authenticated before accessing any resources. JSON Web Tokens (JWT) provide a stateless and secure way to handle authentication in modern web applications. In this post, we’ll take a look at a simple and clean way to apply JWT-based authentication using middleware in a controller constructor.
Let’s break down the following Laravel controller constructor:
public function __construct() {
// Apply JWT middleware to check if the user is logged in
$this->middleware('jwtcustom')->except([]);
// If authenticated, fetch user details and make them available to controller methods
$this->middleware(function($request, $next) {
$this->user = JWTAuth::parseToken()->authenticate();
return $next($request);
})->except([]);
}
🧱 What This Code Does
1. jwtcustom
Middleware
$this->middleware('jwtcustom')->except([]);
This line applies a custom JWT middleware to all routes handled by this controller. It ensures that:
- A valid token is present in the request headers.
- The request is blocked if the token is missing or invalid.
You can specify routes to exclude using the except()
method, but in this case, none are excluded.
2. Fetch Authenticated User
$this->middleware(function($request, $next) {
$this->user = JWTAuth::parseToken()->authenticate();
return $next($request);
})->except([]);
This inline middleware is used to parse the JWT token and retrieve the authenticated user’s details, which are then stored in the $this->user
property for use across other controller methods.
By doing this, you:
- Avoid calling
JWTAuth::user()
multiple times in different methods. - Centralize user authentication logic at the controller level.
🚀 Benefits of This Approach
✅ Keeps authentication logic centralized and clean
✅ Ensures only authenticated users can access controller routes
✅ Makes user data easily accessible in other methods ($this->user
)
✅ Works well with custom middleware for token validation (jwtcustom
)
🛡️ Best Practices
- Token expiration: Ensure you handle expired tokens gracefully.
- Error handling: Add try-catch blocks or global exception handlers for token parsing errors.
- Middleware structure: Keep
jwtcustom
middleware reusable and simple.
📝 Final Thoughts
By leveraging constructor middleware in Laravel, you can apply JWT authentication seamlessly across your API controllers. This approach helps you keep your codebase clean, secure, and efficient.
Would you like a full tutorial on how to build the jwtcustom
middleware or implement refresh tokens? Drop a comment!