Skip to content

Instantly share code, notes, and snippets.

@mustafatoker
Forked from ericlbarnes/laravel-slug.php
Created December 13, 2016 08:27
Show Gist options
  • Save mustafatoker/52dd0dadedde4cac309399c56b19a2a1 to your computer and use it in GitHub Desktop.
Save mustafatoker/52dd0dadedde4cac309399c56b19a2a1 to your computer and use it in GitHub Desktop.
<?php
namespace App\Services;
use App\Post;
class Slug
{
/**
* @param $title
* @param int $id
* @return string
* @throws \Exception
*/
public function createSlug($title, $id = 0)
{
// Normalize the title
$slug = str_slug($title);
// Get any that could possibly be related.
// This cuts the queries down by doing it once.
$allSlugs = $this->getRelatedSlugs($slug, $id);
// If we haven't used it before then we are all good.
if (! $allSlugs->contains('slug', $slug)){
return $slug;
}
// Just append numbers like a savage until we find not used.
for ($i = 1; $i <= 10; $i++) {
$newSlug = $slug.'-'.$i;
if (! $allSlugs->contains('slug', $newSlug)) {
return $newSlug;
}
}
throw new \Exception('Can not create a unique slug');
}
protected function getRelatedSlugs($slug, $id = 0)
{
return Post::select('slug')->where('slug', 'like', $slug.'%')
->where('id', '<>', $id)
->get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment