In Laravel, CSRF (Cross-Site Request Forgery) protection is a security measure that helps to prevent malicious users from making unauthorized requests to your application. Laravel implements CSRF protection by generating a token for each active user session and including the token in a hidden field in every HTML form generated by the application. When a form is submitted, Laravel checks that the token is present and valid, and rejects the request if the token is missing or invalid.
To enable CSRF protection in Laravel, you will need to do the following:
- Include the
@csrf
directive in your forms: To include the CSRF token in your forms, you can use the@csrf
directive. This directive will generate a hidden input field with the CSRF token. For example:
<form method="POST" action="/post">
@csrf
<!-- form fields go here -->
</form>
- Verify the CSRF token: Laravel will automatically check the CSRF token for all non-idempotent HTTP requests (such as POST, PUT, and DELETE). If you want to disable CSRF protection for a specific route, you can use the
except
option in theVerifyCsrfToken
middleware. - Exclude routes from CSRF protection: If you want to exclude certain routes from CSRF protection, you can use the
except
option in theVerifyCsrfToken
middleware or use thecsrf_field()
helper function to include the CSRF token in your form.