Make self-healing URLs with Laravel
The primary principle behind implementing self-healing URLs is being able to segregate the unique identifier (the ID) from the other components of the URL (the SEO-friendly bits). Let's figure out how to do it in Laravel!
Everything I said
I was on Amazon the other day browsing some of my absolute favorite products of all time, and I thought, "This URL, that's pretty nice. I bet that is pretty SEO friendly. I wonder what happens if I take a word out." Nothing. Absolutely nothing happens. I wonder if I can just take all of these words out. You can. You can just take all the words out, and it still loads.
That's pretty cool. I was on Medium, who knows why, whoever comes here anymore, and I thought, "That's a pretty good URL. I bet that's pretty SEO friendly. I wonder if I can take some of those words out." Not only can you take some of those words out, but it will redirect back to the correct spot. It is a self-healing URL.
So that one is probably even better for SEO because it all points back to whatever the current canonical URL is. And I thought, "I wonder if we could do that with Laravel." Spoiler alert, we can. Let me show you how. We're gonna be working with blog posts. I have a simple table that just has a title and a body in it, along with the primary key. And if we go over to the web route, we're just gonna start by saying get, and we'll use Laravel's route model binding.
So we'll say get posts, post. And in here, we're not gonna do anything fancy, 'cause that's not the point of this video. But we will pass through a post and say post, and we'll just return out to the browser post ID and the post body. That should be enough to make it interesting.
We'll give it a name, 'cause we will use this later, and we'll say posts.show. Now, if we hit this in the browser, we should see a Latin post. So we have post ID of one and the body. That's a little bit long. Let's put a colon there and say title, and there you go. That looks good.
So we already have route model binding set up. Thanks to Laravel, we did that in, I don't know, 15 seconds, right? The first thing I wanna do is take a look at this Medium URL. I think we can delete all of that, and it will heal itself. But if we change even a single character over here, there you go. It's a 404. So this is the unique identifier, and we're gonna try to copy that style.
Um, we will put in... What is the title of this? E-R-R, error at Maxime2. So this is what we want. Uh, this is what we, what we want the URL to be, 'cause this is SEO friendly, but it also has the identifier appended to the end. Laravel gives us a couple different ways to hook into route model binding.
One is from the outside in, and one is from the inside out. The outside in is you have the URL, and you're coming in to find the model. The other one is you have the model, and you need to generate the URL. So we're gonna start with we have the URL, and we need to find the model. The place that this logic lives is actually in the eloquent model. So if you come in here, and you say resolveRouteBinding, you'll see that you do get this auto-generated stub.
But if we dump out the value that Laravel has given us, you'll see that that is the string. So because we type hinted the post class, Laravel knows to go to the post model, and it gives us this string and says, "Resolve this. Resolve this string and turn it into a model," which we can definitely do. At this point, all we care about is the ID, so we'll just explode this value.
Love that about PHP, that we call it explode, and we'll use Laravel's last helper to take that and get the ID. And so if we dump out the ID here and see how close we got, great. We got super close. That's what we're looking for, actually. So now we can pass this through to the parent, and we have our post back.
So we're already doing, we're already doing pretty great. We have our nice SEO friendly. We have the Amazon style, where it doesn't actually redirect. So we could put actually anything we want in there, and then as long as we append the ID to the end, we're, we're gonna get, we're gonna get the post. This is not as good as it can be. We're still missing a few other things to make the URL more resilient, and we still need to generate URLs that have that nice slug inside of it, along with the ID, which at this point we're not doing.
Let me show you what I mean by that last point about URL generation. If we just hop over to the web and take over this right here, and we say post equals post find one, and then we just return the route of posts.show, and we pass through the post.
Let's hit that in the browser. So if we just do this, you'll see that it's not generating the nice, pretty URL with the slug. It's generating just the URL with the ID. So we have a couple of things to fix. We're gonna start by fixing that generation, and then we'll look at those self-healing URLs. Back in the post model, if we say getRouteKey, we have two options, getRouteKey and getRouteKeyName.
If we do getRouteKeyName, that is actually telling Laravel which column to look in. We're just gonna do it ourselves. We're just gonna, we're just gonna make this ourselves. So instead of... Actually, let's go look at Laravel and see what it's doing. You'll see that it takes the route key name, and it just calls the get attribute on it. So that's what I mean when I say getRouteKeyName, is if you have a column that is like a specific slug, but we're just gonna make ours up.
So instead of doing any of that, we're gonna do string slug this title, and then we're going to append this ID, and that should be good enough. Look at that. So now we have the, we have the title that's been slugged out, and then the ID has been appended. So we have this nice SEO title, but we still have the direct addressability of the ID there at the end.
The only trick with redirecting here is we can't just return a redirect response like you would from a controller because we're not at that point of the request life cycle. So instead, we're gonna use some of Laravel's built-in helpers to throw an exception that will redirect for us. All right, to show you how this works, let's just throw a new HTTP response exception, and this is just a built-in Laravel exception that accepts a response, and the response that we are gonna give it is a redirect response.
So we're gonna say redirect to, and we're just gonna pass in home. We're just gonna pass in home right now to test, and then we'll pick it up in a second. So if we switch over here and we take the post URL and we put that in, it'll just throw that exception, which redirects us back home. Now we have the ability to throw an HTTP redirect, which is kinda cool, right? We can throw it from anywhere in the HTTP stack, but you do need to make sure that you're not throwing this on the command line, 'cause I actually don't know what would happen.
And we would need to verify that this route model binding only happens as a part of the request-response life cycle, which I'm pretty sure it does, but if I'm wrong, I bet some commenter will tell me, and maybe that commenter can be you. Please tell me if the route model binding happens anywhere outs- outside of the HTTP layer, in which case we would be in trouble.
But we're not in trouble yet, so let's keep moving. We're gonna throw this redirect response as a way to heal these URLs. Now, we only need to throw this exception if the value that's given to us by the router, ph- so the URL value, doesn't match this slug plus ID thing that we generated earlier. So what we can do is we can just yoink that, take that away, move this resolution up a little bit and call it model, and then we can check if model get route key equal equal equals value, then just carry
on, do what you were normally gonna do. Otherwise, throw a redirect. And we still need to do this, and we still need to do... What happens if the model is not found? Um, so we still need to do the 404 handling. But let's check this in the browser first. So if we switch over to the browser, we should see that when we load this URL, that's fine, but when we muck up the slug a little bit and load it again, we are redirected back home.
So off to a pretty good start. We're pulling the model out of the database, and we're checking to see, okay, if I were to generate a URL for this, does it match the URL, the URL that was given to me? If it does, go ahead and show the page. If not, throw a redirect exception. But we have to throw, we have to throw the right exception now. We have to throw the right URL now.
We will update this part down here first. Instead of redirecting home, we can just redirect to a route called post.show, and we've already pulled the model, so we don't even need to fetch it again. Um, and so this should return the correct redirect response for the real URL, not the URL that they gave us. So if we check this in the browser and we change this to some foobar here, hopefully this URL will heal itself, and there you go.
It does. So we, we entered with an incorrect URL, and it redirected us to the correct URL. So we start up here with a value, and we pull the ID off of the incorrect URL, and we get the model. And then we check to see, hey, what is the real URL for this model, and does it match what the user gave us? If so, we hand the model back to Laravel, and we're all done.
If not, we redirect back to the correct URL, and then this actually starts all over again, but this time it will return early here because it does match. The final thing we need to handle here is this for 404. We could do something like abort if and with a 404 if the model doesn't exist. But instead, I'm just gonna return a null to Laravel.
So this resolve route binding does handle the null case, and then Laravel itself will handle the 404 later. So instead of doing anything special, we're just gonna return null. And so now if I type in a bunch of random characters, there you go. We get the 404 that we would expect from default Laravel. The last thing I wanna look at is how do we route on something that is not the ID?
So Medium is using that hash at the end of their URL. We currently have our auto-incrementing primary key, which f- in, in my opinion, is fine to put there. If you think, if you think hiding your primary keys is security, that doesn't move me very much. But I don't think it's very pretty, so we could put a hash there that looks a little bit, a little bit nicer 'cause it's characters instead of just a bunch of numbers.
And so we're gonna add a hash column or a public ID column. There are great ways to generate public IDs, um, that you don't have to have based on the database at all. One scheme is called Nano ID, and there is a package for Laravel, a Nano ID package. We're just gonna use Laravel string random helper, which is good enough for testing but is not random enough for production data.
You will get collisions, and that will cause, uh, that will cause problems. So we're just gonna do, uh, an example here, and then if you wanna use it in production, look into Nano IDs. We're gonna need to change the structure of the post table a little bit. We will add a public ID. We'll move that up, and we'll make that unique. And then we'll go to the post factory over here, and we will make the, we'll make the public ID.
We'll do a string random of 16 is totally fine. Again, you would usually do this in an observer only while you're creating, and you would need a more, uh, random and secure scheme so that you don't have collisions. This is totally gonna have collisions at some point. But for 10 records, it should be just fine.
So if we do DB seed... Oh, we need to do AR migrate fresh seed. That should be good. Now, if we go to... That home route still just shows us, that still just shows us the route of the first model, and so we still see that, that, that trailing one at the end. And so let's hop back to, let's hop back to the post and see if we can figure that out.
Remember, I told you that there was a get route key name. So now we should be able to just return... Actually, let's go again and look at Laravel. get key name. So by default, it does use the primary key. But now in our case, what we're gonna use is we're gonna use the public ID. So if we hop back to the browser, we see that nothing changed, and that's 'cause we've intercepted, we've intercepted the way that Laravel does it, and we've hard-coded ID in there.
So a more robust way to do that would be this getAttribute, this, this get, uh, what's it called? RouteKey name. So now we should see there's our long... Eh, it's a little bit ugly, honestly. Maybe 16 characters is too long. But there is our public ID instead of the auto-incrementing ID.
And if we go posts and drop that in, we see that it does load that first post, which is great. I don't know what the second one is. So if we hop back over to web, we say post find two, and we drop this off. That should be the second post. And so we do get, it wants to translate, we do get the second post, and with any luck, we still get our self-healing.
So if we type Aaron in the middle, it redirects back to the second post. That's pretty cool. Now you know how to create SEO-friendly URLs that will automatically heal themselves if a post title changes or if a product title changes. You don't have to keep around a redom- a redirect map of old titles that need to be redirected to the new ones.
As long as you have that ID at the end, you're good, and that ID can either be your internal auto-incrementing primary key, or you can come up with some sort of public ID scheme if that's how you want to expose that. So hopefully you enjoyed this. If you did, please subscribe to this channel. I've got more Laravel PHP web development content coming all the time. See ya.