To resolve the deprecation warning for csrf() in Laravel, follow these steps:
1. Replace csrf() with csrf_token()
The csrf() helper was deprecated in Laravel 6.1. Use the csrf_token() function instead in PHP code:
// Before (deprecated)
$token = csrf();
// After
$token = csrf_token();
2. Use the Blade @csrf Directive
In Blade templates, replace manual token output with the @csrf directive:
<!-- Before (deprecated) -->
<form method="POST" action="/submit">
{{ csrf() }}
...
</form>
<!-- After -->
<form method="POST" action="/submit">
@csrf
...
</form>
The @csrf directive automatically includes the token in a hidden input field and sets the X-CSRF-TOKEN meta tag for JavaScript.
3. JavaScript AJAX Requests
Ensure the CSRF token is included in AJAX requests by using the meta tag value:
In your Blade layout (e.g., layouts/app.blade.php):
<!-- Ensure this is present -->
<meta name="csrf-token" content="{{ csrf_token() }}">
In JavaScript (e.g., Vue, Axios, or vanilla JS):
// Get the token from the meta tag
const token = document.head.querySelector('meta[name="csrf-token"]').content;
// Include it in AJAX requests
axios.post('/submit', {
// data
}, {
headers: {
'X-CSRF-TOKEN': token
}
});
4. Update Dependencies
If you're using an older Laravel version, consider updating to the latest stable version to benefit from security patches and improvements.
composer update laravel/framework
Key Takeaways:
- Avoid manual token handling wherever possible. Use
@csrf in forms and the meta tag for JavaScript.
- Replace all instances of
csrf() with csrf_token() in PHP code.
- Ensure your codebase is compatible with the latest Laravel version to avoid future deprecation warnings.
By following these steps, you’ll eliminate the deprecation warning and ensure your application uses the recommended CSRF protection methods.