What is CSRF Protection? CSRF protection prevents unauthorized users from submitting forms on behalf of an authenticated user. Laravel includes CSRF protection by default.
Add CSRF Token to Your Form: In every form that submits data, you need to include a CSRF token. Laravel provides the @csrf
directive to automatically insert this token.
Example:
<form method="POST" action="{{ route('submitForm') }}">
@csrf
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<button type="submit">Submit</button>
</form>
The @csrf
directive generates a hidden input field with a token to secure your form.
Validating CSRF Token: When the form is submitted, Laravel automatically checks the CSRF token in the request against the token stored in the session to ensure it’s valid. If invalid, the request is rejected.
Handling CSRF Errors: If the CSRF token is invalid, Laravel throws a TokenMismatchException
. You can customize the error response in the Handler
class.
Example:
public function render($request, Throwable $exception)
{
if ($exception instanceof TokenMismatchException) {
return redirect()->route('formPage')->with('error', 'CSRF token mismatch. Please try again.');
}
return parent::render($request, $exception);
}
Excluding Routes from CSRF Protection (Optional): You can exclude certain routes (like API routes) from CSRF protection by modifying the VerifyCsrfToken
middleware.
Example (in VerifyCsrfToken.php
):
protected $except = [
'api/*',
];
CSRF protection in Laravel ensures that your application’s forms are safe from malicious attacks. By using the @csrf
directive in your forms, you can easily prevent CSRF attacks and secure your application. Always remember to include this token in your forms!