Skip to content

Instantly share code, notes, and snippets.

@r2luna
Created July 20, 2018 21:31
Show Gist options
  • Save r2luna/2b2572a323c904f46072bc59cc568179 to your computer and use it in GitHub Desktop.
Save r2luna/2b2572a323c904f46072bc59cc568179 to your computer and use it in GitHub Desktop.
<?php
namespace App\Services;
use DB;
class SlugService
{
public static function create($title, $table, $id = 0)
{
$slug = str_slug($title);
$allSlugs = static::getRelatedSlugs($slug, $table, $id);
if (!$allSlugs->contains('slug', $slug)) {
return $slug;
}
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 static function getRelatedSlugs($slug, $table, $id = 0)
{
return DB::table($table)
->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