iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌿

Retrieving Typed Data from the Laravel Request Class

に公開
2024/10/18

Introduction

Lately, I've been finding it tedious to manually cast values every time I retrieve them
from the Request class and use them as method arguments, because when
declare(strict_types=1); is specified, it complains about type mismatches.

I was looking through the Pull Requests in laravel/framework
to see if there was a better way and found something interesting, so I'm leaving a note here.

Discovered Pull Request

It's this one:
https://github.com/laravel/framework/pull/44239

It adds methods to retrieve values cast to int or float.

This

intval($request->input('some_int_value'));
(int) $request->input('some_int_value');

floatval($request->input('some_float_value'));
(float) $request->input('some_float_value');

Turns into this.

$request->integer('some_int_value');

$request->float('some_float_value');

It's a small change, but personally, I prefer being able to specify it via a method
rather than writing casts every time.

This feature seems to have been included in Laravel 9.32.

Also, it turns out that boolean, dates, etc., were already retrievable. (I didn't know that.)
https://laravel.com/docs/9.x/requests#retrieving-boolean-input-values

Summary

It's a good idea to check GitHub Issues or Pull Requests when you're stuck.
You might find some kind of solution written there.

I also realized that it's important to revisit the official documentation,
as you can often find new things.

GitHubで編集を提案

Discussion