Created
July 20, 2018 21:31
-
-
Save r2luna/2b2572a323c904f46072bc59cc568179 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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