In this episode, we're finally getting our hands dirty with actually generating a hash ID for the URLs in our project. We kick things off by introducing the hashids php package, which lets us create obfuscated, YouTube-style IDs based on our database records—super useful for building a URL shortener.
First, we walk through pulling in the package, adding it to the project, and quickly demoing how to use it to encode an ID. After that, we talk about two possible approaches for generating and assigning the hash ID: directly within the model or by using a separate utility class. For better organization, we go with the utility class method, creating a HashIdGenerator
class inside a new Utility
folder.
Next, we set up this class to accept a hashids instance in the constructor and then add a generate method. This method grabs the latest URL's database ID, and if there aren’t any records yet, it defaults to 0. We use the hashids package to encode the ID and generate the hash.
We make sure everything is tied together by using the new generator class where IDs are assigned. After confirming it works (IDs are showing up as expected in the database), we tackle the possible issue of conflicts—what if a hash ID isn't unique? To solve this, we wrap the generation process in a do-while loop, incrementing the ID each time until we find a unique one.
By the end of this video, you’ll have a solid, reusable setup for generating short, unique hash IDs for your URLs, ready to be used in your own shortlinks. Next up, we'll look at constructing the redirect URLs for users to actually use!