Laravel CSRF Protection
CSRF protection is a check that a form post comes from your own site. Laravel refuses a form post that has no valid token.
Add the token
The token travels with the form data.
@csrfThe form with a token
The token sits inside the form with the fields.
<form method="POST" action="/l25/hello">
@csrf
<input type="text" name="name">
</form>A post without a token is refused
A form without @csrf has no token to check.
<form method="POST" action="/l25/hello">
<input type="text" name="name">
</form>The route runs with a token
A post with a valid token reaches the route.
Route::post('/l25/hello', function (Request $request) {
return 'Hello, ' . $request->input('name');
});Example
<form method="POST" action="/l25/hello">
@csrf
<input type="text" name="name">
<button type="submit">Say hello</button>
</form>
Route::post('/l25/hello', function (Request $request) {
return 'Hello, ' . $request->input('name');
});Key points
- CSRF: a forged request sent from another site on the reader's behalf.
- Token: a secret value that proves the form came from your own site.
- Use @csrf inside a form to add the token as a hidden field.
- Use the token on every form that posts data.
In this example, the form carries the token from @csrf. The post passes the check and reaches the route. The route greets the reader by name. CSRF protection is a check that a form post comes from your own site.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @csrf add to a form?