Advertisement
julong

#laravel #slug

Sep 7th, 2014
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. public static function getSlug($title, $model) {
  2. $slug = Str::slug($title);
  3. $slugCount = count( $model->whereRaw("url REGEXP '^{$slug}(-[0-9]*)?$'")->get() );
  4. return ($slugCount > 0) ? "{$slug}-{$slugCount}" : $slug;
  5. }
  6. /************************************************************************/
  7. /************************************************************************/
  8. /************************************************************************/
  9. /************************************************************************/
  10. public function setSlugAttribute($value) {
  11.  
  12. $slug = Str::slug($value);
  13.  
  14. $slugs = static::whereRaw("slug REGEXP '^{$slug}(-[0-9]*)?$'");
  15.  
  16. if ($slugs->count() === 0) {
  17.  
  18. return $slug;
  19.  
  20. }
  21.  
  22. // get reverse order and get first
  23. $lastSlugNumber = intval(str_replace($slug . '-', '', $slugs->orderBy('slug', 'desc')->first()->slug));
  24.  
  25. return $slug . '-' . ($lastSlugNumber + 1);
  26.  
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement