I have tried the codes as follows.
$post->title = $request->title;
$post->body = $request->body;
$post->slug = str_slug($post->title,'%');
The code was running great but now I have the post with same title so its throwing error as it is set to unique in db. Is there any way I can get another slug?
If you are facing a slug colision, in this case best way to go would be adding an extra integer at the end example :
mysite.dev/my-post
mysite.dev/my-post-1
For this you could use a package to generate a slug
Of if you want to do it yourself then in the model add slugattribute
public function setSlugAttribute($value) {
if (static::whereSlug($slug = str_slug($value))->exists()) {
$slug = $this->incrementSlug($slug);
}
$this->attributes['slug'] = $slug;
}
So the setSlugAtrribute will always check if the slug for given model exists if so then it will increment the slug as I meantioned above, by simply calling the below method.
public function incrementSlug($slug) {
$original = $slug;
$count = 2;
while (static::whereSlug($slug)->exists()) {
$slug = "{$original}-" . $count++;
}
return $slug;
}
Basically we are always checking if the slug exists in the database, if yes then we use an accessor to change the slug by adding an integer at the end this way you will never end having the slug duplication issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With