Instantly share code, notes, and snippets.

Embed
What would you like to do?
Set the Slug Attribute in Laravel & append counter is not unique
/**
* Set the Slug attribute and add counter if not unique.
* This function will check if the current model's slug is unique and update
* if with a counter at the end of the slug (such as -2) if there already exists.
* For example, if we're saving a page called "About us" with the slug
* "about-us", but for some reason you already have a page with the slug
* "about-us" this new page would then be set to have the slug
* "about-us-2" instead.
*
* @param any $value This is the value passed to this setting function.
*
* @return void
*/
public function setSlugAttribute ($value) {
$model = get_class($this);
$attribute = 'slug';
$default = 'full_name'; // which attribute from the model to pull if no slug set
$empty = $model::all()->where($attribute,$value)->except($this->id)->isEmpty();
if ($value != $this->slug || $this->slug == null || !$empty) {
if ($value == null || empty($value)) {
$value = str_slug($this->$default);
} else {
$value = str_slug($value);
}
if (!$empty) {
$current = explode('-', $value);
$countStart = 1;
if (is_numeric(end($current))) {
$countStart = end($current);
$value = implode("-", array_splice($current, 0, -1));
}
$tempSlug = $value . '-'. $countStart;
for ($i = $countStart; !$model::all()->where($attribute,$tempSlug)->except($this->id)->isEmpty(); $i++) {
$tempSlug = $value . '-' . $i;
}
$value = $tempSlug;
}
$this->attributes[$attribute] = $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment