Skip to content

Instantly share code, notes, and snippets.

@azimidev
Last active November 30, 2017 20:14
Show Gist options
  • Save azimidev/b4317e76de0da47852dbfeb49f4845cb to your computer and use it in GitHub Desktop.
Save azimidev/b4317e76de0da47852dbfeb49f4845cb to your computer and use it in GitHub Desktop.
Laravel Sluggable Trait Version 1
<?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