logo
podcast Podcast
get help Get Unstuck

When does route model binding happen?

Understanding this helps with troubleshooting

Joel Clermont
Joel Clermont
2024-08-14

In yesterday's tip on testing policies, I left out one little "side adventure" that I thought would be worth sharing today.

When I was first trying to test the policy without the middleware interfering, I used the withoutMiddleware helper, but I didn't specify which middleware to disable, so it turned off all of them.

Turning off all middleware changes a lot about how Laravel works, including completely turning off route model binding. I hate to admit it, but it took me about 10 minutes to realize why my test was now failing with a completely different error. Oops!

But I'm not too proud to share my mistakes, especially if it's good inspiration for a tip!

So when does route model binding happen? It is part of the default middleware stack that Laravel defines, and it's right at the end of the list in terms of priority. If you want to take a peek at the code, which I recommend, go find SubstituteBindings in the Laravel source and click around to see how it works in more detail.

The key thing to know is that it happens after the route is matched and before the controller method is called.

Here to help,

Joel

P.S. Tinkerwell is a great tool for poking around Laravel and figuring out how it works. Check it out, and support Mastering Laravel at the same time.

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.