Laravel Slug Helper Generate Unique slug for Laravel
¶Simple Way: Beginner friendly
In Laravel, you can use the Str::slug()
helper method to generate a unique slug for a given string. Here’s an example of how you might use it:
use Illuminate\Support\Str;
$title = 'My Blog Post';
$slug = Str::slug($title, '-');
echo $slug; // Outputs: "my-blog-post"
The Str::slug()
method takes two arguments: the string to convert into a slug, and the character to use as the delimiter. By default, it uses a hyphen (-) as the delimiter.
To make the slug unique, you can check if a slug with the same value already exists in the database, and if it does, append a number to the end of the slug to make it unique. For example:
use Illuminate\Support\Str;
$title = 'My Blog Post';
$slug = Str::slug($title, '-');
$i = 1;
while (Post::where('slug', $slug)->exists()) {
$slug = Str::slug($title, '-') . '-' . $i++;
}
echo $slug; // Outputs: "my-blog-post" (if the slug is unique), or "my-blog-post-2" (if the slug already exists in the database)
This will ensure that the generated slug is always unique, by appending a number to the end of the slug if it already exists in the database.
¶Advanced Way: Best practice way
Hi, let’s make a unique slug helper method to create really nice unique slug in Laravel
Steps:
- Create a folder called
Helpers
insideapp
directory. - Create a file
SlugHelper.php
insideHelpers
directory. - Paste the below codes inside SlugHelper
<?php
namespace App\Helpers;
class SlugHelper
{
/**
* Generate a Unique Slug.
*
* @param string $title
* @param object $model
* @param string $field
* @param string $separator
*
* @return string
* @throws \Exception
*/
public static function generate($model, $title, $field, $separator = "-"): string
{
$id = 0;
$slug = preg_replace('/\s+/', $separator, (trim(strtolower($title))));
$slug = preg_replace('/\?+/', $separator, (trim(strtolower($slug))));
$slug = preg_replace('/\#+/', $separator, (trim(strtolower($slug))));
$slug = preg_replace('/\/+/', $separator, (trim(strtolower($slug))));
// $slug = preg_replace('!['.preg_quote($separator).']+!u', $separator, $title);
// Remove all characters that are not the separator, letters, numbers, or whitespace.
// $slug = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', mb_strtolower($slug));
// Replace all separator characters and whitespace by a single separator
$slug = preg_replace('![' . preg_quote($separator) . '\s]+!u', $separator, $slug);
// Get any that could possibly be related.
// This cuts the queries down by doing it once.
$allSlugs = static::getRelatedSlugs($slug, $id, $model, $field);
// If we haven't used it before then we are all good.
if (!$allSlugs->contains("$field", $slug)) {
return $slug;
}
// Just append numbers like a savage until we find not used.
for ($i = 1; $i <= 10; $i++) {
$newSlug = $slug . $separator . $i;
if (!$allSlugs->contains("$field", $newSlug)) {
return $newSlug;
}
}
throw new \Exception('Can not create a unique slug');
}
private static function getRelatedSlugs($slug, $id, $model, $field)
{
if (empty($id)) {
$id = 0;
}
return $model::select("$field")->where("$field", 'like', $slug . '%')
->where('id', '<>', $id)
->get();
}
}
¶Output example
php artisan tinker
// If Web Designing slug not exist in database, response would be like this
>>> App\Helpers\SlugHelper::generate(App\Models\Category::class, 'Web Designing', 'slug')
=> "web-designing"
// If Web Designing slug exist in database, response would be like this
>>> App\Helpers\SlugHelper::generate(App\Models\Category::class, 'Web Designing', 'slug')
=> "web-designing-1"
>>> App\Helpers\SlugHelper::generate(App\Models\Category::class, 'Web Designing', 'slug')
=> "web-designing-2"
Tags: Laravel Slug Helper Generate Unique slug for Laravel, new slug laravel, laravel awesome slug, laravel slug
PHP If-else-elseif and Switch-case
PHP String Functions - All necessary String functions in PHP to manage strings better.
Popular Tutorials
Popular Tutorials
Categories
-
Artificial Intelligence (AI)
11
-
Bash Scripting
1
-
Bootstrap CSS
0
-
C Programming
14
-
C#
0
-
ChatGPT
1
-
Code Editor
2
-
Computer Engineering
3
-
CSS
28
-
Data Structure and Algorithm
9
-
Design Pattern in PHP
2
-
Design Patterns - Clean Code
1
-
E-Book
1
-
Git Commands
1
-
HTML
19
-
Interview Prepration
2
-
Java Programming
0
-
JavaScript
12
-
Laravel PHP Framework
37
-
Mysql
1
-
Node JS
1
-
Online Business
0
-
PHP
28
-
Programming
8
-
Python
12
-
React Js
19
-
React Native
1
-
Redux
2
-
Rust Programming
15
-
Tailwind CSS
1
-
Typescript
10
-
Uncategorized
0
-
Vue JS
1
-
Windows Operating system
1
-
Woocommerce
1
-
WordPress Development
2
Tags
- Artificial Intelligence (AI)
- Bash Scripting
- Business
- C
- C Programming
- C-sharp programming
- C++
- Code Editor
- Computer Engineering
- CSS
- Data Structure and Algorithm
- Database
- Design pattern
- Express JS
- git
- Git Commands
- github
- HTML
- Java
- JavaScript
- Laravel
- Mathematics
- MongoDB
- Mysql
- Node JS
- PHP
- Programming
- Python
- React Js
- Redux
- Rust Programming Language
- TypeScript
- Vue JS
- Windows terminal
- Woocommerce
- WordPress
- WordPress Plugin Development