ahmadmayahi
1 month ago
186
6
Laravel

A question about the validated() method in the request

Posted 1 month ago by ahmadmayahi

Hey,

I need to treat the published_at field (which is coming from the Http request) as a Carbon instance.

This is what I did in the App\Http\Requests\CreatePostFormRequest:

public function validated()
{
    return array_merge(
        parent::validated(),
        [
            'published_at' => Carbon::createFromFormat('Y-m-d', $this->input('published_at')),
        ]
    );
}

So this is how I save it in the controller:

public function store(PostFormRequest $request, CreatePostAction $action)
{
    $action->execute(PostData::fromRequest($request));
    // ...
}

The PostData class is a DTO:


class PostData extends DTO
{
    protected static array $ignoreProps = [
        'slug',
    ];

    public string $title;

    public string $content;

    public Carbon $published_at; // in DTO it has to be an instance of Carbon

    public int $author_id;

    public string $slug;
}

The question is:

Is it (normal) to modify the validated() method in the request?

If not, how do you do it? what is the (better) way of doing it?

Best, Ahmad

Please sign in or create an account to participate in this conversation.