July 202523:5912.9k views

Hacking the Laravel router

About

🚨 Unfortunately, this won't work when routes are cached.

We dive into the Laravel core and hack together a feature I’ve always wanted, route bindings that gracefully fall through if a model isn’t found. Along the way, I show how to safely extend Laravel with macros and custom validators without breaking future upgrades.

Transcript

Everything I said

00:00

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.

00:23

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 podcasts/episodes and then an episode parameter, and that goes to the episode controller.

00:44

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.

01:04

Let me show you in the browser what this looks like so far. Wow, beautiful. I'm still working on this. This is, uh, I've not yet deployed this, but I am very happy with it. So this is /podcasts, and it shows all podcasts, and you get down here and you're like, "Oh, I can pick. That's nice. Let me pick Mostly Technical." Cool, it changed. So we have all of these down here, and the URL changes up there.

01:27

I haven't updated the videos yet, but that's okay. This is great for the podcast, but then, like I said earlier, I've gotta hit episodes/two, and I just... I don't want that. What I, in fact, want is I want this to be super ultra tilted. I want it to be like that with the title of the podcast.

01:50

But we can't do that. So here's what we're going to invent. We're going to invent ignore missing bindings. That's what I wanna do. That is the entire thing that I wanna do. This is different than Laravel's built-in, um... Laravel has a built-in missing thing where you can say, like, return, redirect to, you know, podcasts, whatever.

02:17

Right? So inside of a single route, you can say, "Hey, if this binding is missing, let's do something about it." But what you can't do is say, like, uh, keep looking for other routes that might match. That's what we wanna do. We wanna keep looking for more routes because we want it to fall through down to here.

02:41

And you can imagine if, um... Let's go down to writing. You can imagine that if we've got, uh, let's say, articles and tutorials, we could have, uh, you know, we could have tutorial. We could have tutorial go to the tutorial, which doesn't exist, tutorial controller. We could have writing, uh, tweets, and you could have it go to the tweet controller.

03:05

And so you've got all of these similar URLs that actually are going off to different places to grab different models, and we just need it to fall through and say, like, "Hey, if you don't find an article, that's fine. Keep going. Keep looking for something else." All right, this is what we're going to build. Not missing, we're gonna build ignore, uh, ignoreMissingBindings.

03:27

I think that is what we wanna call it. Um, now we gotta figure out how are we actually going to do this. And we're 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 and see if there's a place we can add it. Before we do that, I do need to thank the sponsor for this episode, and that is Bento.

03:51

I use Bento for all of my email needs, both marketing and transactional. We use it in our business. I use it for my newsletter. Uh, the support over at Bento is amazing. I'm constantly getting support from the founder himself. So if you need an email service provider for business or personal use, please check out Bento at bentonow.com and tell him that I sent you.

04:16

All right, let's get back to some Laravel. The first thing I am going to do, because if we can't, i-i-if we can't do this next part, it doesn't matter. The first thing I'm gonna do is I'm gonna see, uh, if we can add macros to this route. So let's go in here, and it looks like, um... Let's see. What is name return?

04:37

Name returns a route, and there we go. That's what I'm looking for. So this is the actual class. So we're down in source illuminate routing route. So not the facade, but the actual, um, underlying class. And hey, whoo, thank goodness this was gonna be a short video. It's macro-able. So we can go ahead and, uh, let's do this in the app service provider.

05:02

And we'll say, you see I've already got some other macros for stuff. Uh, route macro, and then what did we call it? We called it ignoreMissingBindings. So we'll say ignoreMissingBindings, and we gotta do something. To do. So now that we have ignoreMissingBindings, we can hit, uh, we can have Laravel Idea, um, generate the helper code for that.

05:29

And if we go back to web, there we go. ignoreMissingBindings is there. Oh. What do we do now? Um, well, it's off, it's off to a good start. Um, so we need to find, we need to find where these bindings actually happen. Let's come back out here, um, and we need to, let's see, um, try to perform the binding, and if we get an error, figure out

05:59

how to, uh, figure out how to signal that we should keep looking. Okay? That is- That's kind of what we want to do, but I think in reality here, here, we just want to, um, mark that this route should ignore bindings, and then somewhere else we'll have to do that part.

06:24

So we need to figure, figure out where to store this info. All right, so we are in route. Let's go look at route. Let's see what we have available to us. I'm familiar with some of this. I'm not familiar with all of it. Um, I am familiar with the route action array. So if we, um, we... This is how I always do this, by the way.

06:45

This is exactly how I do this. Right click, find usages. I want, where are we writing to the action array? It looks like in the constructor is one part. Okay? So by the time the route is constructed, this action array should be filled. We can't just add a property to this class because it doesn't have that dynamic properties, uh, attribute, which is fine.

07:15

We can store this information in the action array. So let's come back out here, 'cause we're trying to figure out where are we gonna store this flag basically that says ignore missing bindings. So if I DD this, um, this get action. Yeah, okay. So we can... There's a getter. What does this getter look like? It just... Oh, cool.

07:35

That's a, um, an array helper method. So if we pass nothing, it'll return the entire array, which sh- should be good. That's what we're looking for. Cool. This is... You can see we're in the app service provider, and we have all of this stuff. So it looks like this is the place where all the good information is stored. Uses, controller, namespace, prefix, where, as.

07:57

You know what we're gonna do? We're just gonna shove a new key in there. Um, so I need the app service provider, and I'm gonna say, uh, this action ignore missing bindings equals true. And then if I DD this get action, we'll see if it's persisted. Ignore missing bindings.

08:18

Cool. So now on this route alone, we are storing this information. Um, I'm fairly confident this is always going to be an array, since it is set up as an array in the constructor. Array accept, parse action. Yeah, so I feel pretty good that that's always gonna be, that's always gonna be available to me.

08:41

Now, the question is, when we see that flag, what do we do? We have to go deep dive into Laravel's routing mechanism to figure out how are these routes matched, right? So a request comes in, and Laravel has to look through each individual route to see if it matches. And is there a place we can hook in to say, "Actually, this one doesn't match.

09:06

Um, I know that you think it matches, but it doesn't match. Don't throw an error, just keep looking. Keep looking for more, 'cause this ain't it." Let's see if we can find that. All right, so I'm gonna go to route, and I'm gonna look for, um... I'm just gonna look and see what all the methods are. Why not? So, uh, that's Command R here, and I don't want inherited members, 'cause that's gonna add all the macro stuff.

09:28

So I'm gonna look through here, and I'm gonna see is there anything that looks useful. Fallback might be useful, but I think that is, um, I think that's if no routes match in your whole application, you put that at the very bottom. Um, matches. That looks right.

09:49

Determine if the route matches a given request. This is great. This is what we want. Okay. So it's gonna come in here, um, presumably. Let's see, find usages on this guy. Method call. There we go. The route collection. Okay, so it takes all the routes, it puts the fallbacks in, and it finds the first one that matches.

10:17

That is exactly the part we're trying to hook into. Um, we can't do anything... I don't wanna make my own route class that extends this route, 'cause that's gonna be a nightmare to keep up with. So I'm trying to hook in without causing any consumers of this code, which in this case is just me, without causing any consumers of the code to have secret knowledge.

10:43

I don't want them to have to know, hey, whoa, whoa, whoa, in this, in this project, we don't use Laravel routes, we use Aaron routes. It's like, that's stupid. I don't want that. So compile route, what do you do? To Symphony route compile. Um, all right. I think that's a red herring. Now, this is interesting.

11:05

Um, so this matches is supposed to return a Boolean, and we loop through the validators. Who are you? What do you do? And if a validator doesn't match, we return false, which is what we want, right? We wanna say, "This route doesn't match." Um, so that's interesting.

11:29

And if all of the validators pass, then we return true and say, "Yes, this is the right route. Send me the request." So let's look at self get validators. Okay, um, good. This is looking very good, because we see that it is, um, returning the static validators, which if this is public, we are in luck.

11:53

If this wasn't public, we could add a macro to access it from the inside. It's a little, it's a little wonky, but we don't have to do that. Um, so this is, uh, just a local cache where it's just setting it, and if it's present, return it. Otherwise- This is exactly what we need. Um, so it validates the URI, which I imagine is the regex.

12:17

Yeah, so it, it validates the regex, then it validates to make sure that, um, your... If it's accepting posts, uh, it's making sure the request is a post. Scheme is probably HTTP versus HTTPS, and host is probably, I guess that's, like, domain probably. Who knows? Who can say? These are the validators.

12:37

Um, validators look very simple. They just have a matches. Okay, that's cool. Validator interface just has a matches. We're gonna write our own validator. That's what we're gonna do. Uh, let's hop out to HTTP routing, and we're gonna do new, um... Let's do... What do we wanna call this? Um, let's do this.

12:59

Let's do ignore, uh, bindings validator. Aha. We can clean this up if we don't like this. Implements validator interface and Illuminate routing matching. Yes. So now we will need to... We can close you. We need to implement method stubs, um, and then we'll just say, here we are.

13:24

Okay. We will receive the route and the request. Now, how do we get it into Laravel? That's the question. So we can see here that we short circuit if these static validators are set. That's a good thing. Okay? So that means, um, we can hook in and set the validators.

13:45

Now, one super important principle when I'm mucking around is, uh, I want this to be as future-proof as possible. I don't, I don't wanna screw everything up, and I don't wanna create a maintenance burden for myself. So what I'm not gonna do is take these and copy them and then add my own validator. What I am going to do is I'm gonna come out here, um, and I can do this.

14:11

Route get validators. And I can say that, uh, the validators are that, and then I can do route validators equals, uh, the validators plus my ignore bindings validator. And then I can clean this up just a tiny bit and say, there we go.

14:38

So now what I've done is I don't care what Laravel does in version 13, 15, 16, 17, or 14. I don't know why I skipped that. Um, I'm fine, and I'm always gonna put mine last. So I'll put mine last because mine could be expensive, and if the URI doesn't even match or the, the method doesn't even match, let's get out of here.

14:58

Let's bail early. So now, presumably, I should see DD here on every route, and I freaking do. Okay. Um, so we're hooked in. We're totally hooked into Laravel. Um, all we've done is add a new validator in here. Now we gotta figure out, um...

15:18

Let's see. If route. Let's do, uh, w- let's do this. DD route get action. Okay? And ignore missing bindings. All right. So, um, and we can use, because it is a helper, we can use that, and we should see... Yep.

15:39

And by default, can we do a default? No, it just gives us a key. That's fine. Um, so if we're not ignoring missing bindings, we can just return true, 'cause we're not like... We're, we're not doing anything. We're just saying, "Yeah, this doesn't actually apply here." Um, okay.

16:00

Otherwise, we need to ignore missing bindings. Ignore missing bindings on podcast/guest. Yes, that is right. Now, how are we gonna, how are we gonna ignore missing bindings? That's a good question. We have to figure out how Laravel is doing the route binding, uh, the route model binding.

16:24

Let's go back to the route and search for binding. Scoped, enforces scoped, binding, binding, binding, binding. Okay. Now I'm gonna come out here. Um, I'm actually just gonna look for a class called... Hey, that looks good. Substitute bindings.

16:46

Substitute bindings. Okay. Where do you get used? It looks like you are a, you are a middleware, so I bet you're just used somewhere in the default stack. Um, come on. Figure it out. Search, search, search. Show me the default.

17:07

There we go. You are used in, there you go, middleware groups and the kernel. Um, middleware priority, substitute bindings, middleware groups, substitute binding. So it's part of the web stack, substitute bindings is. Can we steal it?

17:30

Can we use it? All right. So it looks like it is, um, constructed, and it's passed in the registrar. That's fine. We can use app construct to do that, and then it handles the request. Um, it handles the request, and it takes... This is the, uh, this is the middleware signature, so that's, that's to be expected there.

17:53

Um, this is close. I think all we need is this part right here. So let's take, uh... Let's try to, like... Let's split this vertically, and let's come back to ours. And let's do it like this.

18:15

Um, we are gonna take... What are you? You are the registrar. So we're gonna say that, uh, registrar equals, uh, App-RoutingRegistrar. Yep, that's right. So that is that part, and then we can come down here and just take you guys.

18:38

And instead of, um... Ah, we can name it router, 'cause that's what Laravel names it. We can say... We can do that. Now, I don't think that's gonna work. Um, but what I wanna do is I wanna say, catch ModelNotFound. Um, and we'll just say, Not Found, and passed.

19:07

I think this is going to fail, but let's see. Um, so podcast guest route is not bound. What does that mean? Okay, so on our, on our specific, uh... When we're trying to mimic this SubstituteBindings middleware, we get this error, and the error is route parameters, and it goes into parameters, and then it says, "The parameters are not set.

19:34

Route is not bound." That's fine. We can figure things out. Let's go to route and look for, um, is there a bound? Nope. Is there a bind? There is a bind. Look at that. Cool. So we can bind. It looks like we need to bind a request into the route, um, to make it able to access the parameters.

19:58

That's that thing it was trying to access where it couldn't be set. Now, again, I don't wanna muck anything up, um, and I don't know exactly what goes on in the Laravel core. So what I'm gonna do, clone route bind request, and I'm actually just gonna...

20:20

Sure, j- let's just override it. Um, I don't care. So what I've done is I've taken the route that came in, which, um, is an object, and so if I dork around with it, that could persist through the rest of the life cycle. I don't really want that. So I'm gonna bind, um, the request into a cloned version of the route, and then we'll substitute the bindings, and these should, um...

20:44

No, it takes me to a contract. I do hate that. Um, let's see. SubstituteBindings. Yeah, so those should throw a ModelNotFound exception. Now, there could be, uh, on the route, there could be something that says, "If you find a... Or if there is a ModelNotFound exception, here's the handler for that." So we need to account for that much.

21:06

Um, let's come back here, and we'll say, if it ignores missing bindings or if it has a MissingBindingHandler unto itself, we're just gonna say, "Yeah, this passes the validator, Laravel. Like, do your thing. That's fine." Um, so now we're safe down here, and I think if we hit refresh again, we should no longer see...

21:29

Cool. Yeah. Nice. That, that, that's great. Now, if we type in, um, that, we get, "Not Found." Hey, that's pretty cool. Did we update, um... Yeah, podcast/episode and podcast/podcast. Cool. So we updated that. Now, what I'm wondering is if we typed in foobar, it still says, "Not Found," which is good, because it's saying that for that podcast

22:00

route, it was not found. Okay. Um, so we can say that this route is not the correct route. We're just gonna say, "Nope, nope, nope. Keep looking. This one's not a match." Remember, all of this rolls up into that matches, uh, method, and so we can just say, "Hey, I don't know, man. Keep looking. Find somebody else." Now, if we do return true there, we should see, um, invalid, uh, context.

22:30

Where are you coming from? So, hey, oh, it worked. SELECT * FROM episodes WHERE id equals foobar LIMIT 1. So it fell through. I think it worked. It fell through from this one and went down to this one and tried to look up an episode in the database using a string, which apparently is not allowed, 'cause I bet I'm routing by ID.

22:56

It works. So now, uh, if I do mostlytechnical, 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 is extremely flexible and extremely customizable, especially when you find that macroable trait.

23:25

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.

23:47

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.

Laravel & PHP

More videos on Laravel & PHP

All videos

Get the next one by email

I’ll send you some more. Not too many.

Join 7,500+ other readers.

Read past issues