Skip to content

Instantly share code, notes, and snippets.

@PiotrKrzyzek
Last active February 14, 2018 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PiotrKrzyzek/eab5134c4cd2b994c5d6ba5a69f0b526 to your computer and use it in GitHub Desktop.
Save PiotrKrzyzek/eab5134c4cd2b994c5d6ba5a69f0b526 to your computer and use it in GitHub Desktop.
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