Last active
November 30, 2017 20:14
-
-
Save azimidev/b4317e76de0da47852dbfeb49f4845cb to your computer and use it in GitHub Desktop.
Laravel Sluggable Trait Version 1
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 | |
/** | |
* For this to work you don't need to do anything, | |
* just add this Sluggable Trait inside your Model | |
*/ | |
namespace App\Traits; | |
trait Sluggable | |
{ | |
/** | |
* Get the Slug instead of id | |
* | |
* @return string | |
*/ | |
public function getRouteKeyName() | |
{ | |
return 'slug'; | |
} | |
/** | |
* Create slug upon creation. | |
*/ | |
public static function bootSluggable() | |
{ | |
static::creating(function ($model) { | |
$model->slug = make_slug($model->title); | |
$latestSlug = static::whereRaw("slug RLIKE '^{$model->slug}(-[0-9]*)?$'") | |
->orderBy('id') | |
->pluck('slug'); | |
if ( ! $latestSlug->isEmpty()) { | |
$pieces = explode('-', $latestSlug); | |
$number = (int) end($pieces); | |
$model->slug .= '-' . ($number + 1); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment