logo
podcast Podcast
get help Get Unstuck

Our rule for ordering controller action parameters

With an explanation as to why

Joel Clermont
Joel Clermont
2024-06-12

You can inject a few different kinds of parameters into a controller action in Laravel.

  • Route parameters injected as bound models or as raw values
  • The request object, either a generic request or a form request
  • Other services or dependencies to be resolved from the container

The order you specify these in the method signature does not matter to Laravel, but it does matter to me.

What order do we use in our projects?

  1. First, we list any route parameters, in the order they appear in the route definition.
  2. Then, we list the request object, and the vast majority of the time this is a form request doing some authorization or validation.
  3. Finally, we list any other dependencies that the method will need.

Why this particular order? It is how I think about Laravel executing the request.

When the request comes in, and it gets matched to a route, the route model binding happens at the same time.

Then the form request's authorize and validate methods are called by the framework.

Finally, and only if the previous two steps pass, will the controller action be invoked and the remaining parameters be used.

Again, it doesn't really matter as far as Laravel is concerned, but I like the simplicity and consistency of this approach.

Here to help,

Joel

P.S. Want someone to be meticulous and thorough on your project? We would love to help you level up your Laravel project.

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.