How I hacked Laravel to ignore missing route bindings
Ever wish Laravel would just keep looking when a route binding fails? I implemented a custom ignoreMissingBindings macro to hook into the Laravel Core. Perfect for anyone who’s ever wanted graceful fall-through in their routes.
🚨 Unfortunately, this won't work when routes are cached.
Everything I said
We're gonna hack a little bit on the Laravel core, adding a feature that I certainly want, and I don't know if anyone else in the world wants, but that is not the point. The point is you can figure things out. That's the point. So we're gonna go dive into the source of Laravel and see if there's anywhere that we can get our grubby little paws on this process to kind of, uh, shoehorn our new feature into it. So let me show you what we're actually trying to do.
Here is my routes file, and we're gonna look at this podcast section here. So very normal stuff. We've got podcasts with an optional podcast parameter that goes to the podcast controller. We've got podcast/episodes and then an episode parameter, and that goes to the episode controller. I don't like this. I don't want it to be like this. I want it to be like that. But we can't put, we can't put, um, this first because then if it doesn't match an episode, we get a 404.
We can't put this second because then if it doesn't match a podcast, we get a 404. So we're gonna, we're gonna try to fix it. Just gonna start by poking around. We're not gonna go on a forum and ask a question. We're not gonna ask ChatGPT. We're not gonna go on Twitter and complain. We can figure things out, so we're just gonna go source dive, see if there's a place we can add it. Works.
So now, uh, if I do mostly technical, I get the podcast page, and if I do the number two, I get an episode page. We have just successfully ignored missing bindings. This is super cool. I hope this encourages you that, one, Laravel's extremely flexible and extremely customizable, especially when you find that macro-able trait.
We love to see that. And two, you can figure anything out. All you gotta do is source dive, look around, hook into the life cycle, drop a few DD statements in there. It's the best way to debug. And you can get your grubby little paws on almost every part of the Laravel framework to add anything that you need. Let me know what you think, uh, about this video and also about the method. Would you use it? It's not big enough to turn into a package, but if somebody wants to make a PR to the framework, I would 100% support you.
Until the next time. See ya.