Dorokhov.codes

09. Working with forms

Getting data

Instead of using direct access to the arrays:

$_GET['email'];
$_POST['email'];
$_REQUEST['email'];

we should do it using the \Illuminate\Http\Request object:

$request->input('email'); // returns null if the field is absent

Get all data:

$request->all();

Get only certain fields:

$request->only(['username', 'email']);

Get all fields except some of them:

$request->except('password');

It’s convenient to use the boolean() method to accept checkbox values:

$request->boolean('remember'); // the input() method is used under the hood

Validation

There are a useful validate method provided by the Illuminate\Http\Request object.

If the validation rules pass, your code will keep executing normally; however, if validation fails, an Illuminate\Validation\ValidationException exception will be thrown. Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors and request input will automatically be flashed to the session.

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

@error directive:

<input
    id="title"
    type="text"
    name="title"
    class="@error('title') is-invalid @enderror"
/>
 
@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

Replacing the sending method

We need to add to a form a hidden input with name _method and a value of the desired method.

<input type="hidden" name="_method" value="PUT">

Adding the field:

<form method="get">
    @method('POST')
</form>

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">
    <!-- Generates the CSRF token hidden input field -->
    @csrf
</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.

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');