Skip to content

Instantly share code, notes, and snippets.

@minedun6
Created August 17, 2018 13:19
Show Gist options
  • Save minedun6/f976cf0bb50d2582dbfdba0ed8aaf3c2 to your computer and use it in GitHub Desktop.
Save minedun6/f976cf0bb50d2582dbfdba0ed8aaf3c2 to your computer and use it in GitHub Desktop.
Create unique slug with #Laravel using the tutorial made by @teamcodecourse
<?php
namespace App\Traits;
trait Sluggable {
public static function bootSluggable() {
static::creating(function ($model) {
$model->slug = (new static)->generateUniqueSlug($model->name);
});
}
protected function generateUniqueSlug($name) {
$slug = str_slug($name);
$number = 1;
while($this->query()->where('slug', $slug)->exists()) {
$slug = str_slug($name) . '-' . $number++;
}
return $slug;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment