Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Services;
  4.  
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Support\Collection;
  7. use Illuminate\Support\Str;
  8.  
  9. /**
  10. * Class SlugService
  11. * @package App\Services
  12. */
  13. class SlugService
  14. {
  15. /**
  16. * Get current slugs from storage
  17. *
  18. * @param Model $model
  19. * @param string $field
  20. * @return Collection
  21. */
  22. protected function getSlugs(Model $model, string $field = 'slug'): Collection
  23. {
  24. return get_class($model)
  25. ::select($field)
  26. ->get()
  27. ->pluck($field);
  28. }
  29.  
  30. /**
  31. * Build a new unique slug string
  32. *
  33. * @param string $prefix
  34. * @param Collection $existing
  35. * @return string
  36. */
  37. protected function buildSlug(string $prefix, Collection $existing): string
  38. {
  39. $counter = 1;
  40.  
  41. $slugWithCounter = $prefix;
  42.  
  43. while ($existing->contains($slugWithCounter)) {
  44.  
  45. $slugWithCounter = $prefix . '-' . $counter;
  46. $counter++;
  47.  
  48. }
  49.  
  50. return $slugWithCounter;
  51. }
  52.  
  53. /**
  54. * Get a unique slug for the provided model
  55. *
  56. * @param Model $model
  57. * @param string $source
  58. * @param string $field
  59. * @return string
  60. */
  61. public function uniqueSlug(Model $model, string $source = 'title', string $field = 'slug'): string
  62. {
  63. $slugs = $this->getSlugs($model, $field);
  64.  
  65. $slug = Str::slug($model->{$source});
  66.  
  67. return $this->buildSlug($slug, $slugs);
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement