Himanshu SharmaSoftware engineer
Let’s talk

Laravel · Lesson 12 of 40

Laravel forms and CSRF protection

Build an HTML form that posts to Laravel, understand why the CSRF token is required, use method spoofing for PUT and DELETE, and redirect with a flash message.

14 minViews, forms and validationUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonBuild the Pagelane Books contact form with a CSRF token, handle the POST in a controller, redirect with a status message, and explain what a 419 means.

What you can do after this lesson

You will build a working form: Pagelane Books gets a contact page. You will understand the hidden token that every Laravel form carries and why leaving it out produces the 419 error from the routing lesson.

The contact form

Add two routes and a controller. The routes (in routes/web.php):

php
Route::get('/contact', [ContactController::class, 'create'])->name('contact.create');
Route::post('/contact', [ContactController::class, 'store'])->name('contact.store');
bash
php artisan route:list --path=contact
text
  GET|HEAD   contact ............... contact.create › ContactController@create
  POST       contact ................. contact.store › ContactController@store

Both share one URL; the method decides which runs. This is a normal pattern: GET shows the form, POST receives it. The view, resources/views/contact/create.blade.php:

blade
<x-layout title="Contact">
    <h1>Contact the shop</h1>

    <form method="POST" action="{{ route('contact.store') }}">
        @csrf

        <p>
            <label for="name">Name</label><br>
            <input id="name" name="name" type="text">
        </p>
        <p>
            <label for="email">Email</label><br>
            <input id="email" name="email" type="email">
        </p>
        <p>
            <label for="message">Message</label><br>
            <textarea id="message" name="message" rows="5"></textarea>
        </p>
        <button type="submit">Send</button>
    </form>
</x-layout>

Use <label for> linked to each field's id, so screen readers and click targets work. The name attributes become the keys you read with $request->input('name'). In the layout, a status line is shown when the session holds one:

blade
@if (session('status'))
    <p class="card" role="status">{{ session('status') }}</p>
@endif

The controller

php
class ContactController extends Controller
{
    public function create(): View
    {
        return view('contact.create');
    }

    public function store(Request $request): RedirectResponse
    {
        $name = $request->input('name');

        return redirect()
            ->route('contact.create')
            ->with('status', "Thanks, {$name}. We will reply soon.");
    }
}

This version does not check the input. The next lessons add validation and then email; keep in mind that printing the name is safe because Blade escapes it, but accepting anything is not. After handling the POST, the method redirects rather than rendering a page. This is called post-redirect-get: if the user refreshes the final page, the browser repeats a harmless GET instead of resubmitting the form. ->with('status', ...) stores a flash message in the session that is available on the next request only.

What CSRF is, and the token

Cross-site request forgery (CSRF) is an attack where another website makes your logged-in browser send a request to your site. A hidden form on an evil page could submit to /account/delete, and your browser would helpfully attach your session cookie. The defence is a secret token tied to your session, included in each form. A forged request from another site does not know the token.

@csrf prints it as a hidden input:

bash
curl -s -c jar.txt http://127.0.0.1:8091/contact | grep -E "<form|_token"
text
    <form method="POST" action="http://127.0.0.1:8091/contact">
        <input type="hidden" name="_token" value="5vFVSOJQ6bR..." autocomplete="off">

(The token value is random and shortened here; yours differs every session.) Now compare a POST without the token and a POST with it:

bash
curl -s -o /dev/null -w "%{http_code}\n" -X POST -d "name=Ada" http://127.0.0.1:8091/contact
curl -s -i -b jar.txt -d "_token=THE_TOKEN&name=Ada&email=ada@example.com&message=Hi" http://127.0.0.1:8091/contact
text
419
HTTP/1.1 302 Found
Location: http://127.0.0.1:8091/contact

Without the token Laravel answers 419; with the cookie jar (which keeps the same session) and the token, the request is accepted and redirects. Following the redirect, the page contains Thanks, Ada. We will reply soon., and a second reload shows no message, because flash data lives for one request.

Laravel's release notes say that in Laravel 13 the request forgery protection middleware was formalised as PreventRequestForgery, adding origin-aware checks while staying compatible with token-based protection. The practical rule for you is unchanged: every state-changing form needs @csrf. Do not disable CSRF checks for convenience. If you build a JavaScript front end, Laravel also sets an XSRF-TOKEN cookie (you saw it in the response headers) that scripts can echo back in a header.

Method spoofing

HTML forms can only submit GET and POST. For updates and deletes, keep the form POST and add a hidden _method field with the @method directive:

blade
<form method="POST" action="{{ route('books.update', $book) }}">
    @csrf
    @method('PUT')
    ...
</form>

Verified with a throwaway route Route::put('/spoof', fn () => 'PUT reached'):

text
PUT reached      (POST with _token and _method=PUT)
405              (plain POST to the same URL)

Laravel reads _method and dispatches to the PUT route; a plain POST to that URL answers 405 Method Not Allowed. You will use this in the book edit and delete forms later.

Common mistakes

  • Forgetting @csrf. The classic cause of 419 in a new form.
  • Disabling CSRF protection to "fix" a 419 instead of adding the token.
  • Rendering a page directly from a POST handler. Redirect afterwards so a refresh does not resend the data.
  • Testing with curl and no cookie jar. The token belongs to a session, so you must send the same session cookie back.
  • A form that uses method="PUT" directly. Browsers treat that as GET.
  • Using GET for forms that change data, such as a delete link.

Exercise

Change the store method so the flash message mentions the email too (Thanks, Ada (ada@example.com)...) and verify the flow with curl, with and without a cookie jar.

Show one possible answer
php
$name = $request->input('name');
$email = $request->input('email');

return redirect()
    ->route('contact.create')
    ->with('status', "Thanks, {$name} ({$email}). We will reply soon.");

With a cookie jar the follow-up GET shows the message once; without the -b cookie jar the flash is lost, because a new session starts on every request. That is why a browser, which keeps cookies, works and bare curl calls do not. Next: validating input.

Key points

  • Add the csrf directive inside every POST, PUT, PATCH and DELETE form; it prints a hidden _token field that Laravel checks against the session.
  • A web request with a missing or wrong token is rejected with status 419, protecting users from forged cross-site requests.
  • HTML forms only send GET or POST, so the method directive adds a hidden _method field that Laravel uses to route PUT, PATCH and DELETE.
  • The post-redirect-get pattern, redirecting after a successful POST, stops duplicate submissions when the user refreshes.
  • redirect()->with() stores a flash message for exactly one following request, shown with session('status').

Check yourself

1. What is the purpose of the @csrf directive in a form?
2. A form without a token is submitted to a web route. What happens?
3. How do you make an HTML form send a DELETE request to Laravel?
4. Why redirect after handling a POST?