← Back to Course

Protecting Against CSRF Attacks

Cross-Site Request Forgery (CSRF) tricks a logged-in user's browser into submitting a request they never intended to make. Laravel guards against this automatically for any state-changing request.

The CSRF Token

Every session gets a unique CSRF token, and Laravel checks that token on every POST, PUT, PATCH, and DELETE request submitted through a form.

<form method="POST" action="/profile">
    @csrf
    ...
</form>

The @csrf directive outputs a hidden input containing the token, which Laravel's VerifyCsrfToken middleware then validates automatically.

Handling AJAX Requests

<meta name="csrf-token" content="{{ csrf_token() }}">
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').content;

Excluding Routes

Certain routes, like webhook endpoints from external services, may need to bypass CSRF checks. These can be listed in the $except property of VerifyCsrfToken.

CSRF protection covers request forgery, but keeping user accounts safe also depends on how passwords themselves are stored — which is the next topic.

Ready to master Laravel Training Course?

Join Uncodemy's hands-on Laravel program and build real, production-ready applications.

Explore Course