logo
podcast Podcast
get help Get Unstuck

Better types on route parameters

More docblocks banished

Joel Clermont
Joel Clermont
2024-12-26

I just noticed a new feature that was added in a recent weekly Laravel 11 release that allows me to clean up a few more docblocks in my code.

This is in the same spirit as my tip last week about getting config values with type safety.

Laravel added a new RouteParameter attribute which can be placed on a parameter in either the rules or authorize methods of a form request:

// before - with a docblock
public function rules(): array
{
    /** @var Product $product */
    $product = $this->route('product');
    
    // rules omitted for brevity
}

// after - with the new attribute
public function rules(#[RouteParameter('product')] Product $product): array
{
    // no docblock needed! $product is already typed
}

If you're not yet using attributes, the syntax might take a little bit to get used to, but I really like this improvement.

Not only does it eliminate the need for a docblock, but I can now scan the method signature and see exactly what parameters from the route are being used.

It's the same thing I like about injecting dependencies into controller methods or jobs.

One last note: as of right now, this attribute only works on form requests, and only in the rules and authorize methods. It's not a general-purpose attribute for any method or class, at least not yet.

Here to help,

Joel

P.S. One thing I enjoy about conferences is talking with random developers and hearing what they're working on. It can inspire me to try something new or point out something I didn't know. No need to wait for the next Laracon. Get that every day in the Mastering Laravel community.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.