Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 67 ยท Views and Blade

Forms, CSRF and Assets with Vite

Build safe Laravel forms with @csrf, @method, @error and old(), then bundle CSS and JavaScript with Vite and Tailwind 4 using @vite, npm run dev and build.

Two things turn a Blade template into a real page: forms that send data back safely, and CSS and JavaScript that reach the browser. Laravel gives you a small set of tools for each. For forms there is @csrf (protection against forged requests), @method (HTML forms only know GET and POST), old() (keep what the user typed) and @error (show validation messages). For assets there is Vite, the build tool that ships with every new Laravel application.

Laravel code cannot run on this site, so the real framework snippets are read-only. Two plain-PHP stand-ins are runnable: one checks CSRF tokens the way the framework's middleware does, and one renders a form with old input and errors.

A complete form

Here is a typical "edit profile" form. Every part is explained below the code.

BLADE
<form method="POST" action="{{ route('profile.update') }}">
    @csrf
    @method('PUT')

    <label for="name">Name</label>
    <input id="name" name="name" value="{{ old('name', $user->name) }}"
           @class(['border-red-500' => $errors->has('name')])>
    @error('name')
        <p class="text-red-600">{{ $message }}</p>
    @enderror

    <label for="email">Email</label>
    <input id="email" type="email" name="email" value="{{ old('email', $user->email) }}">
    @error('email')
        <p class="text-red-600">{{ $message }}</p>
    @enderror

    <button type="submit">Save</button>
</form>
  • route('profile.update') builds the URL from a named route, so the form never contains a hard-coded path.
  • @csrf prints a hidden field named _token holding the current session's CSRF token.
  • @method('PUT') prints a hidden _method field. Browsers only submit GET and POST, so Laravel reads _method on a POST request and treats it as PUT, PATCH or DELETE.
  • old('name', $user->name) returns what the user submitted on the previous request, if validation failed and sent them back, and otherwise the default (the saved value).
  • @error('name') runs its body only when that field has an error, and makes the first message available as $message. $errors->has('name') and $errors->first('name') give the same information in expressions.

The old() and $errors data comes from the session, as described in sessions and flash data. The validation lesson shows how the redirect back with errors happens.

What CSRF is, and what @csrf does

Imagine you are logged in to your bank in one tab, and another tab holds a page with a hidden form that posts to bank.example/transfer. Your browser attaches your session cookie to that request, so without protection the bank would obey it. This is cross-site request forgery. The defense is a secret that the attacker's page cannot read: a token the server put in its own form.

sequenceDiagram
    participant B as Browser
    participant S as Laravel
    B->>S: GET /profile
    S-->>B: HTML with hidden _token
    B->>S: POST /profile with _token
    Note over S: token equals the session token?
    S-->>B: 200 OK, or 419 Page Expired

The form carries a secret that a forged page on another site cannot know. A missing or wrong token ends in a 419 response.

In Laravel the CSRF middleware (named PreventRequestForgery in Laravel 13; VerifyCsrfToken still exists as a deprecated subclass) is part of the web middleware group. For every verb except GET, HEAD and OPTIONS it lets the request through if any of these hold:

  1. The browser says the request is same-origin, using the Sec-Fetch-Site header.
  2. A token in the _token input or in an X-CSRF-TOKEN or X-XSRF-TOKEN header matches the session's token (compared with hash_equals).
  3. The URI is on the exclusion list.

Otherwise it throws a token mismatch exception and the visitor sees 419 Page Expired. A form that works for hours and then suddenly fails usually means the session expired while the page was open.

The stand-in below follows the same decision. It is not the real middleware, just the logic in a few lines.

PHP A CSRF check in miniature

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Real Laravel generates a fresh random token for each session and also sets an encrypted XSRF-TOKEN cookie that JavaScript libraries such as Axios read and send back as a header, so ordinary AJAX calls work without extra code. For fetch() you can read the token from a meta tag:

BLADE
<meta name="csrf-token" content="{{ csrf_token() }}">

Routes that must accept outside POSTs, such as a payment webhook, are listed in bootstrap/app.php. Keep that list as short as possible and verify such requests another way (for example a signature):

PHP
<?php

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware): void {
    $middleware->preventRequestForgery(except: [
        'webhooks/stripe',
    ]);
})

Showing old input and errors

The second stand-in renders the form fields with old() and @error logic, with a plain $flash array in place of the session. In real Laravel the validation redirect stores the input and errors in the session for exactly one more request.

PHP old() and error messages in a form

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The suspicious name "><script> comes back as harmless text because old() output goes through {{ }}, which escapes it. Never print old input with {!! !!}. Also notice that password fields are never refilled: do not call old() for them.

Assets with Vite

Browsers need compiled CSS and JavaScript, and during development you want changes to show instantly. Vite does both. Your source files live in resources/css/app.css and resources/js/app.js; Vite builds them into public/build for production, or serves them from a dev server with hot reloading while you work. The @vite directive writes the right tags in each situation.

BLADE
<head>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
flowchart LR
    S["resources/css/app.css<br/>resources/js/app.js"] --> V["Vite"]
    V -->|"npm run dev"| D["Dev server with hot reload<br/>(public/hot file exists)"]
    V -->|"npm run build"| B["public/build<br/>(hashed files + manifest)"]
    D --> T["@vite prints tags<br/>pointing at the dev server"]
    B --> U["@vite prints tags<br/>from manifest.json"]

While npm run dev is running, @vite points the page at the dev server; otherwise it reads the production manifest.

Three commands cover everyday work:

Terminal
npm install        # once, to fetch dependencies
npm run dev        # development: leave it running while you code
npm run build      # production: writes hashed files to public/build

The build output includes a manifest.json, so @vite can add the hashed file names (app-3f9a1c.css) and let browsers cache them for a long time. If a page fails with "Unable to locate file in Vite manifest", the file is not in the build output: run npm run build, or start npm run dev, and check that the path in @vite matches an entry in vite.config.js.

Tailwind CSS 4 setup

Current Laravel starter projects use Tailwind CSS 4 through its Vite plugin, so there is no tailwind.config.js and no PostCSS setup. The setup is two small pieces:

JavaScript
// vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import tailwindcss from '@tailwindcss/vite';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
        tailwindcss(),
    ],
});
CSS
/* resources/css/app.css */
@import 'tailwindcss';

@source '../../storage/framework/views/*.php';

@theme {
    --font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif;
}

@import 'tailwindcss' loads the framework, @source tells Tailwind which extra files to scan for class names (Blade templates in resources/views are found automatically, and the compiled-views line covers classes used in packages), and @theme defines your design tokens as CSS variables. If you install a new project with a starter kit, all of this is already done for you.

With the CSS in place, Tailwind classes work in any Blade file, for example the classes in @class(['rounded px-3 py-2', 'bg-red-50' => $errors->any()]). Only classes that appear as complete strings in your files are generated, so never build names like "bg-" . $color . "-500".

Common mistakes

  • Forgetting @csrf in a POST form, which gives a 419 page.
  • Using @method('PUT') on a form whose method attribute is GET: the spoof only works on POST.
  • Printing old() values with {!! !!}, which opens an XSS hole.
  • Refilling password fields with old().
  • Deploying without running npm run build, so @vite cannot find the manifest.
  • Committing the public/hot file or leaving npm run dev running on a production server.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @csrf output?

    @csrf prints a hidden _token field. The middleware compares it with the token stored in the session.
  2. 2. Why does a form that edits a record need @method('PUT')?

    The form itself is sent as POST, and Laravel treats the request as PUT because of the _method field.
  3. 3. What status does Laravel return when the CSRF token is missing or wrong?

    A token mismatch produces 419 Page Expired, often after a session timeout on an open form.
  4. 4. What happens to @vite when npm run dev is running?

    While the dev server runs, a hot file exists and @vite prints tags that load assets from it. Without it, @vite uses the production manifest.
  5. 5. Where is Tailwind CSS 4 loaded in a typical Laravel project?

    Tailwind 4 needs no config file by default. The Vite plugin plus one CSS import is enough, and @theme holds customizations.

Summary

  • A Blade form needs @csrf for POST, PUT, PATCH and DELETE, and @method for verbs other than GET and POST.
  • old('field', $default) refills the form after a failed validation; @error('field') shows its message.
  • The CSRF middleware accepts a matching token (input or header), a same-origin request, or an excluded URI; otherwise the answer is 419.
  • Vite compiles resources/css and resources/js; @vite prints dev-server or manifest tags.
  • Use npm run dev while coding and npm run build for deployment.
  • Tailwind 4 needs the Vite plugin and @import 'tailwindcss' in your CSS.

Next: Validation