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...