Why I always type-hint route parameters

A fun little riddle

Joel Clermont
Joel Clermont

In a recent code review discussion, I was asked why I was type-hinting a model property in a controller action, even though I wasn't even using it in that method.

It's a valid question, and to be honest, I didn't do it at first. But I bumped into something unexpected that made me realize why it's still useful.

Let's say you have a route with two parameters, like this:

Route::get('/posts/{post}/comments/{comment}', [CommentController::class, 'show']);

Inside your controller action, you are only using the Comment model, and not using the Post parameter at all.

But, what if something else is using that route parameter? Let's say a form request is accessing $this->route('post') and then using it for validation or authorization logic.

If you don't type-hint the post parameter in the controller action, $this->route('post') will return a string containing the plain URL parameter. This is most certainly not what you want.

But if you type-hint the post parameter, now you'll get the actual model instance in the form request. This is true for anywhere you're going to access the route param: a policy, middleware, the constructor controller, and so on.

Even though these two pieces of code might not seem related, they definitely are.

Here to help,


P.S. Form requests and validation rules are a topic I have explored in great depth. Check out our book, learn something new, and support the newsletter.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.