Skip to content

Refactor attempts to get request data to use type-specific methods when the type is known#403

Open
imliam wants to merge 5 commits into
driftingly:mainfrom
imliam:typed-request-data
Open

Refactor attempts to get request data to use type-specific methods when the type is known#403
imliam wants to merge 5 commits into
driftingly:mainfrom
imliam:typed-request-data

Conversation

@imliam

@imliam imliam commented Oct 4, 2025

Copy link
Copy Markdown
Contributor
-$name = $request->input('name');
-$age = (int) $request->get('age');
-$price = (float) $request->data('price');
-$isActive = (bool) $request['is_active'];
+$name = $request->string('name');
+$age = $request->integer('age');
+$price = $request->float('price');
+$isActive = $request->boolean('is_active');

@alexey-m-ukolov

Copy link
Copy Markdown

I like the idea just want to point out that $request->input('name') and $request->string('name') are not the same - former returns (in this example) string|null and latter returns \Illuminate\Support\Str.
I'm not sure if this case should be handled at all - even if we replace with $request->string('name')->toString() we are still losing null. I think only the explicit casts and calls like $request->input('name', '') can be safely replaced (with added ->toString()).

Comment on lines +11 to +14
$name = (string) $request['name'];
$age = (int) $request['age'];
$price = (float) $request['price'];
$isActive = (bool) $request['is_active'];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might want to consider what happens if null coalese is used:

Suggested change
$name = (string) $request['name'];
$age = (int) $request['age'];
$price = (float) $request['price'];
$isActive = (bool) $request['is_active'];
$name = (string) $request['name'];
$age = (int) $request['age'];
$price = (float) $request['price'];
$isActive = (bool) $request['is_active'];
$name = (string) ($request['name'] ?? null);
$age = (int) ($request['age'] ?? null);
$price = (float) ($request['price'] ?? null);
$isActive = (bool) ($request['is_active'] ?? null);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants