Last active
February 14, 2018 01:50
-
-
Save PiotrKrzyzek/eab5134c4cd2b994c5d6ba5a69f0b526 to your computer and use it in GitHub Desktop.
Set the Slug Attribute in Laravel & append counter is not unique
This file contains 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
/** | |
* 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