Create Unique Slugs from Title in Laravel

Rinku Dogra January 10, 2020

Create Unique Slugs from Title in Laravel

In this article, we will explain the easiest way to make your blog posts URLs with unique slugs created from the title of the particular post. You can use this function in the PHP based Laravel framework.

Below is the function you need to put in the controller file. You need to pass your post title as a parameter in the function:


public function createUniqueSlug($title)
{
// Normalize the title
$slug = str_slug($title);
// Get any that could possibly be related.
// This cuts the queries down by doing it once.
$allSlugs = $this->getRelatedSlugs($slug, $id);
// If we haven't used it before then we are all good.
if (! $allSlugs->contains('slug', $slug)){
return $slug;
}
// Just append numbers like a savage until we find not used.
for ($i = 1; $i contains('slug', $newSlug)) {
return $newSlug;
}
}
}

//Function is used to get all the related slugs from database.
protected function getRelatedSlugs($slug)
{
return Post::select(‘slug’)->where(‘slug’, ‘like’, $slug.’%’)->get();
}

Here is the breakdown of the above function createUniqueSlug().

Primarily, We are converting the post title to lowercase by using str_slug function.

Moreover, The getRelatedSlugs() function used to get the related posts of same URL or slug. This will return you all the posts which have the same slug.

However, in the next step, we will check if $allSlugs contains the slug of the same post. If it does, then go with the next step, where the “for” loop will return a new slug.

Now your slug is ready you can store that slug in the database.

Do share it with your friends if you found this article helpful!

If you have any queries or doubts about how to create unique slugs from titles in Laravel, please feel free to contact us. We are here to help you!

Lets’s Talk

About your ideas and concept