[Video] Laravel $request->integer() vs input(): Type Casting: Practical Examples

PREMIUM
Premium Video (20 mins)
Subscribe to Premium to watch the full video

This tutorial is available in both video format above, and in the text article below.


In Laravel Controllers, we often call $request->input() method, right? But also, there are specific methods for strict types: $request->integer(), $request->boolean(), and others. What is the real benefit of using them? Let me explain, with examples.

The main thing is that $request->input() always returns string. Even for numbers, booleans, dates, etc. This causes type mismatches that break strict comparisons, crash foreach loops, and send inconsistent data to your front-end.

Let's look at each of the type-strict methods, and what real bugs may happen if we don't use them.


1. $request->integer()

By default, Laravel's input() method returns string values, not integers, even when the parameter looks like a number:

// URL: /products?page=5
$page = $request->input('page'); // Returns "5" (string), not 5 (integer)

This behavior can lead to critical issues that often go unnoticed until production. One example is with APIs returning strings, confusing frontend code:

// URL: /blog?page=5
$page = $request->input('page', 1); // Returns "5" (string)
return response()->json([
'current_page' => $page, // String "5" in JSON
'per_page' => 10, // Integer 10 in JSON
]);

The Problem: Frontend JavaScript receives inconsistent types:

// Response: {"current_page": "5", "per_page": 10}
if (data.current_page === 5) { // False! "5" !== 5
// Never executes
}

2. $request->date()

When having a date from a request, you can cast it to an Illuminate\Support\Carbon using the date() method. For example, when registering, you need to verify the user's age.

In the frontend, you have a date input:

<input name="birthdate" type="date" placeholder="YYYY-MM-DD" required />

To work with the date, you need to parse it manually into a Carbon instance.

$birthdate = \Illuminate\Support\Carbon::parse($request->date('birthdate'));

Instead, you can let Laravel...

The full tutorial [20 mins] is only for Premium Members

Login Or Become a Premium Member for $129/year or $29/month
What else you will get:
  • 83 courses
  • 98 long-form tutorials
  • access to project repositories
  • access to private Discord

Recent New Courses