What is CSRF in Laravel

What is CSRF in Laravel

Imagine you're logged into your bank website in one tab. In another tab, you visit a shady website. That site secretly sends a request to your bank to transfer money—without you knowing! 😲

This trick is called Cross-Site Request Forgery (CSRF). Laravel protects you by using CSRF tokens—like secret passwords that only your site knows.

How Does Laravel Check CSRF Tokens?

Laravel gives each user a CSRF token and checks it with every request. If the token is missing or wrong, Laravel blocks the request to prevent attacks.

Adding CSRF Token in Forms

Laravel automatically includes the CSRF token in forms using @csrf:

<form action="/submit" method="POST">
    @csrf
    <button type="submit">Send</button>
</form>


Using CSRF Token in AJAX Requests 

If you are handling AJAX requests, include the token in the request header:

$.ajax({
    url: "/submit",
    type: "POST",
    data: { key: "value" },
    headers: { "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr('content') },
    success: function(response) {
        console.log(response);
    }
});


Disabling CSRF Protection for Specific Routes

If you need to disable CSRF protection for certain routes (not recommended for security reasons), add them to $except in app/Http/Middleware/VerifyCsrfToken.php:

protected $except = [
    'webhook/*',
];



Comments