Created
August 17, 2018 13:19
-
-
Save minedun6/f976cf0bb50d2582dbfdba0ed8aaf3c2 to your computer and use it in GitHub Desktop.
Create unique slug with #Laravel using the tutorial made by @teamcodecourse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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