4,000 emails/month for free | Mailtrap sends real emails now!

Primitive Types in Controllers and Closure Routes

Published on by

Primitive Types in Controllers and Closure Routes image

Something I’ve not considered is type-hinting primitive types in Laravel controllers. PHP only has four scalar primitive types: bool, int, float, and string—regarding routes, string and int are the most likely types you’d want. However, I usually don’t type-hint scalar primitive types in my controllers.

I recently saw an issue crop up with type-hinting controller actions caused by a TypeError, so I’d like to demonstrate a few examples where you can safely use type-hinted controllers with the int type.

Consider the following route action and think about what type the $orderId will be when called:

Route::get('/order/{order_id}', function ($orderId) {
return [
'type' => gettype($orderId),
'value' => $orderId,
];
});

The $orderId will be a string when this closure is called. If you write a quick test, this is what you’ll see passing:

/**
* A basic test example.
*
* @return void
*/
public function test_example()
{
$response = $this->get('/order/123');
 
$response->assertJson([
'type' => 'string',
'value' => '123',
]);
}

Now, let’s say that you expect the order id always to be an integer, so you want to type-hint the parameter:

Route::get('/order/{order_id}', function (int $orderId) {
return [
'type' => gettype($orderId),
'value' => $orderId,
];
});

If you go back to your test, it will now fail with the following output:

--- Expected
+++ Actual
@@ @@
array (
- 'type' => 'string',
- 'value' => '123',
+ 'type' => 'integer',
+ 'value' => 123,
)

Although we technically pass a string of 123 to the route function, PHP handles this by default via type coercion. In other words, PHP tries to convert our value from a string to an integer when calling the route function.

Though technically this approach will work and guarantee a type of integer, we still have another issue you may have spotted: what if the user passes something that cannot convert from a string to an integer?

If we update our test to the following, we will get a TypeError:

public function test_example()
{
$this->withoutExceptionHandling();
 
$response = $this->get('/order/ABC-123');
 
$response->assertJson([
'type' => 'integer',
'value' => 123,
]);
}

Running the test will give you the following error:

TypeError: Illuminate\Routing\RouteFileRegistrar::{closure}():
Argument #1 ($orderId) must be of type int, string given, called in .../vendor/laravel/framework/src/Illuminate/Routing/Route.php on line 238

If we want to type-hint an integer in a route, we should ensure our route has a regular expression constraint:

Route::get('/order/{order_id}', function (int $orderId) {
return [
'type' => gettype($orderId),
'value' => $orderId,
];
})->where('order_id', '[0-9]+');

After adding the route parameter constraint, only numeric values will match the route, thus ensuring type coercion works as expected. The following test will be more accurate to ensure you cannot match the order route with a non-numeric router parameter:

public function test_example()
{
$response = $this->get('/order/ABC-123');
 
$response->assertNotFound();
}

Now you can assume that your closure route’s type safely coerces to an integer if you want to use type-hinting. Though the use-case is limited, I think learning about this nuance could help people trying to type-hint router parameters.

How is This Affected By Strict Types?

I’d like to point out that declare(strict_types=1); has no effect since the calling code is within the Laravel framework which does not use the strict_types declaration, thus type coercion will occur:

  1. Laravel’s Controller::callAction() for controllers
  2. Laravel’s Route::runCallable() for closure-based routes

In PHP’s type declarations documentation, Strict typing has the following note about how strict types work:

Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function defined in a file with strict typing, the caller’s preference (coercive typing) will be respected, and the value will be coerced.

Alternative Approaches

If you have scalar routing parameters in controllers and closures, you can omit scalar types and do type-casting within your controller method:

Route::get(
'/order/{order_id}',
function ($orderId, SomeService $someService) {
// Cast for a method that strictly type-hints an integer
$result = $someService->someMethod((int) $orderId);
// ...
}
);

Most of the time, you’ll use route model binding for route parameters matching numeric IDs; however, consider this approach when you have a numeric route parameter that you want to type-hint with a primitive scalar type int.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Battle Ready Laravel

The ultimate guide to auditing, testing, fixing and improving your Laravel applications so you can build better apps faster and with more confidence.

Visit Battle Ready Laravel
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Laravel 12.44 Adds HTTP Client afterResponse() Callbacks image

Laravel 12.44 Adds HTTP Client afterResponse() Callbacks

Read article
Handle Nested Data Structures in PHP with the Data Block Package image

Handle Nested Data Structures in PHP with the Data Block Package

Read article
Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup image

Detect and Clean Up Unchanged Vendor Files with Laravel Vendor Cleanup

Read article
Seamless PropelAuth Integration in Laravel with Earhart image

Seamless PropelAuth Integration in Laravel with Earhart

Read article
Laravel API Route image

Laravel API Route

Read article
Laravel News 2025 Recap image

Laravel News 2025 Recap

Read article