Advertisement
Guest User

Untitled

a guest
Jan 16th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Services;
  4.  
  5. use App\Post;
  6.  
  7. class Slug
  8. {
  9. /**
  10. * @param $title
  11. * @param int $id
  12. * @return string
  13. * @throws \Exception
  14. */
  15. public function createSlug($title, $id = 0)
  16. {
  17. // Normalize the title
  18. $slug = str_slug($title);
  19.  
  20. // Get any that could possibly be related.
  21. // This cuts the queries down by doing it once.
  22. $allSlugs = $this->getRelatedSlugs($slug, $id);
  23.  
  24. // If we haven't used it before then we are all good.
  25. if (! $allSlugs->contains('slug', $slug)){
  26. return $slug;
  27. }
  28.  
  29. // Just append numbers like a savage until we find not used.
  30. for ($i = 1; $i <= 10; $i++) {
  31. $newSlug = $slug.'-'.$i;
  32. if (! $allSlugs->contains('slug', $newSlug)) {
  33. return $newSlug;
  34. }
  35. }
  36.  
  37. throw new \Exception('Can not create a unique slug');
  38. }
  39.  
  40. protected function getRelatedSlugs($slug, $id = 0)
  41. {
  42. return Post::select('slug')->where('slug', 'like', $slug.'%')
  43. ->where('id', '<>', $id)
  44. ->get();
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement