How to Create or Generate Slugs in Laravel ?
A slug is a simplified version of a title or phrase that is usually converted into a lowercase, hypernated format.
For example, if you have a post titled “How to learn Laravel efficiently”, the corresponding slug would be:
how-to-learn-laravel-efficiently
Generating Slugs using Str::slug()
(Laravel 8.x and Later)
In Laravel 8.x and beyond, Str::slug()
is the go-to method for generating slugs. The Str
class is part of the Laravel framework, including the slug()
method.
use Illuminate\Support\Str;
$title = 'How to Learn Laravel Efficiently';
$slug = Str::slug($title); //Output: 'how-to-learn-laravel-efficiently'
The Str::slug()
function will automatically convert the string into lowercase and replace spaces with hyphens, making it suitable for URLs.
Create a Slug Manually in PHP:
$string = preg_replace('/[^A-Za-z0-9\-]/', '-', $request->slug); //Removed all Special Character and replace with hyphen
$final_slug = preg_replace('/-+/', '-', $string); //Removed double hyphen
$slug = strtolower($final_slug);
return $slug;
This method is a straightforward way to generate slugs manually in PHP.