Guest User

Untitled

a guest
Feb 25th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. /**
  2. * Set the Slug attribute and add counter if not unique.
  3. * This function will check if the current model's slug is unique and update
  4. * if with a counter at the end of the slug (such as -2) if there already exists.
  5. * For example, if we're saving a page called "About us" with the slug
  6. * "about-us", but for some reason you already have a page with the slug
  7. * "about-us" this new page would then be set to have the slug
  8. * "about-us-2" instead.
  9. *
  10. * @param any $value This is the value passed to this setting function.
  11. *
  12. * @return void
  13. */
  14. public function setSlugAttribute ($value) {
  15. $model = get_class($this);
  16. $attribute = 'slug';
  17. $default = 'full_name'; // which attribute from the model to pull if no slug set
  18.  
  19. $empty = $model::all()->where($attribute,$value)->except($this->id)->isEmpty();
  20. if ($value != $this->slug || $this->slug == null || !$empty) {
  21. if ($value == null || empty($value)) {
  22. $value = str_slug($this->$default);
  23. } else {
  24. $value = str_slug($value);
  25. }
  26.  
  27. if (!$empty) {
  28. $current = explode('-', $value);
  29. $countStart = 1;
  30. if (is_numeric(end($current))) {
  31. $countStart = end($current);
  32. $value = implode("-", array_splice($current, 0, -1));
  33. }
  34. $tempSlug = $value . '-'. $countStart;
  35. for ($i = $countStart; !$model::all()->where($attribute,$tempSlug)->except($this->id)->isEmpty(); $i++) {
  36. $tempSlug = $value . '-' . $i;
  37. }
  38. $value = $tempSlug;
  39. }
  40.  
  41. $this->attributes[$attribute] = $value;
  42. }
  43. }
Add Comment
Please, Sign In to add comment