What is a slug?
A slug is an SEO friendly URL often created by replacing using the title of a post and replacing titles with hyphens.
First ensure you have a column to store the slug in your database and on your model.
If you don't run a migration
You can easily crate a slug using
Laravel had a Slug helper method which can be used but generally you also want to check for duplicate slugs -- and append a suffix -- when they are automatically generated
$slug = Str::slug('$request->$title', '-');
There are several package that will take care of this for you and other best practices in generating slug
composer require cviebrock/eloquent-sluggable
php artisan vendor:publish --provider="Cviebrock\EloquentSluggable\ServiceProvider"
php artisan config:clear
add the sluggable method to the Post model. This assumes you have a column slug in table associated with the model
use Cviebrock\EloquentSluggable\Sluggable;
class Post extends Model
{
use HasFactory, Sluggable;
public $fillable = [
'title',
'body',
'slug',
'user_id'
];
/**
* Return the sluggable configuration array for this model.
*
* @return array
*/
public function sluggable(): array
{
return [
'slug' => [
'source' => 'title'
]
];
}
this will even work really nicely with your factoryies