Laravel CSRF Protection (Cross-Site Request Forgery) 🔒
Laravel includes CSRF (Cross-Site Request Forgery) protection by default to prevent malicious attacks.
1. How CSRF Protection Works?
CSRF attacks trick users into performing unintended actions (e.g., deleting an account) without their knowledge.
Laravel protects against this by:
✅ Generating a CSRF Token for each session.
✅ Verifying the Token on form submissions.
2. CSRF Token in Forms (Blade Templates)
To include a CSRF token in POST, PUT, PATCH, DELETE requests, add this inside forms:
✅ Example:
<form action="/submit" method="POST">
@csrf
<input type="text" name="name" placeholder="Enter Name">
<button type="submit">Submit</button>
</form>
What @csrf
does?
It adds a hidden input field with a token:
<input type="hidden" name="_token" value="generated_csrf_token">
When the form is submitted, Laravel checks if the token is valid.
3. CSRF Protection in AJAX Requests
When using JavaScript/AJAX, you need to include the CSRF token manually.
✅ Example with jQuery AJAX:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post('/submit', { name: 'John' }, function(response) {
console.log(response);
});
✅ Ensure CSRF Token in <head>
(Blade File)
<meta name="csrf-token" content="{{ csrf_token() }}">
4. CSRF Middleware (Laravel Internals)
Laravel automatically verifies CSRF tokens for all POST, PUT, PATCH, and DELETE requests using the middleware:
📄 File: app/Http/Middleware/VerifyCsrfToken.php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
protected $except = [
// Add routes to exclude from CSRF verification
];
}
✅ Exclude a Route from CSRF Protection
If needed, you can bypass CSRF verification for specific routes:
protected $except = [
'webhook/stripe',
'api/*'
];
5. Disabling CSRF for API Routes
Since APIs use stateless authentication (JWT, Sanctum, etc.), CSRF protection is not needed for api.php
.
📄 File: routes/api.php
Route::post('/create-user', [UserController::class, 'store']);
✅ Ensure API Routes are Excluded in Middleware
📄 File: app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
'api/*'
];
6. CSRF Token Expiry Issues (AJAX Solutions)
If users stay on a page for too long, the CSRF token may expire, causing 419 Page Expired errors.
✅ Solution: Auto-refresh CSRF Token (JS)
setInterval(() => {
fetch('/refresh-csrf').then(response => response.json()).then(data => {
$('meta[name="csrf-token"]').attr('content', data.csrf_token);
});
}, 300000); // Refresh every 5 minutes
✅ Route to Refresh Token
📄 File: routes/web.php
Route::get('/refresh-csrf', function() {
return response()->json(['csrf_token' => csrf_token()]);
});
7. CSRF Token in Postman & API Clients
When making POST requests using Postman, you must disable CSRF for API routes (api.php
) or manually send the CSRF token as a header:
X-CSRF-TOKEN: generated_csrf_token
Conclusion
✅ Laravel automatically protects against CSRF.
✅ Always use @csrf
in Blade forms.
✅ Add CSRF headers for AJAX requests.
✅ Exclude API routes if needed.
🚀 Need more help? 😊
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.