Laravel Forms and CSRF

Laravel Forms and CSRF

Laravel makes it easy to build HTML forms and automatically protects them from Cross-Site Request Forgery (CSRF) attacks.

1 - Creating a Form in Blade

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

    <div>
        <label for="title">Title</label>
        <input type="text" id="title" name="title" value="{{ old('title') }}">
    </div>

    <div>
        <label for="body">Body</label>
        <textarea name="body">{{ old('body') }}</textarea>
    </div>

    <button type="submit">Save</button>
</form>

2 - CSRF Token

// @csrf outputs a hidden input with a token
// Laravel automatically verifies it on POST/PUT/PATCH/DELETE requests

// For JavaScript requests, read the token from the meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">

// Or include in Axios globally:
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').content;

3 - Method Spoofing

// HTML forms only support GET and POST.
// Use @method() for PUT, PATCH, or DELETE:

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

4 - Repopulating Form Values

// old() returns the previous input after a failed validation
<input name="title" value="{{ old('title', $post->title) }}">

// For checkboxes:
<input type="checkbox" name="published" {{ old('published', $post->published) ? 'checked' : '' }}>