Dorokhov.codes

12. Requests

Injection with \Illuminate\Http\Request.

Get a value:

$request->input('title');

Get all data:

$request->all();

CSRF

By default, any POST, PUT, PATCH, or DELETE request in Laravel’s web routes needs to include a CSRF token parameter to protect against Cross-Site Request Forgery (CSRF) attacks.

Laravel provides built-in CSRF protection by generating a CSRF token for each session, and this token must be sent with any mutating (changing data) requests.

How to include CSRF token into the form:

<form method="POST" action="/your-route">
    @csrf <!-- Generates the CSRF token hidden input field -->
    <!-- Other form fields -->
    <button type="submit">Submit</button>
</form>

How to include CSRF token into the request header:

const csrfToken = '{{ csrf_token() }}';

$.ajax({
    url: '/your-route',
    type: 'POST',
    headers: {
        'X-CSRF-TOKEN': csrfToken
    },
    data: {
        // Your AJAX request data
    }
});

Laravel generates a new CSRF token for each session, and this token remains the same until the session expires or the user logs out.

Approach

We can include this token into the head of the document.

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

And get it using jQuery:

const csrfToken = $('meta[name="csrf-token"]').attr('content');