freekmurze / freek-dev-comments

2 stars 0 forks source link

1721-customising-and-extending-laravel-form-requests #38

Open utterances-bot opened 4 years ago

utterances-bot commented 4 years ago

Customising and extending Laravel Form Requests - Freek Van der Herten's blog on PHP, Laravel and JavaScript

Freek Van der Herten is a developer and partner at Spatie.

https://freek.dev/1721-customising-and-extending-laravel-form-requests

shomisha commented 4 years ago

Hey Freek, great video, I learned a few things from it. A great example for custom public methods on form requests are datetime fields that are submitted with date and time separate but stored in a single field, check it out:

<?php

namespace App\Http\Requests;

use Carbon\CarbonImmutable;
use Illuminate\Foundation\Http\FormRequest;

class SomeRequestWithDateTime extends FormRequest
{
    public function rules()
    {
        return [
            'start_date' => ['required', 'date_format:Y-m-d'],
            'start_time' => ['required', 'date_format:H:i'],
            'end_date' => ['required', 'date_format:Y-m-d'],
            'end_time' => ['required', 'date_format:H:i'],
        ];
    }

    public function getStartDate(): CarbonImmutable
    {
        return CarbonImmutable::createFromFormat(
            'Y-m-d H:i',
            $this->input('start_date') . ' ' . $this->input('start_time')
        );
    }

    public function getEndDate(): CarbonImmutable
    {
        return CarbonImmutable::createFromFormat(
            'Y-m-d H:i',
            $this->input('end_date') . ' ' . $this->input('end_time')
        );
    }
}