Skip to content

Instantly share code, notes, and snippets.

@azimidev
Last active November 30, 2017 20:15
Show Gist options
  • Save azimidev/daef8950ff41efb62878cfaa633f0f0d to your computer and use it in GitHub Desktop.
Save azimidev/daef8950ff41efb62878cfaa633f0f0d to your computer and use it in GitHub Desktop.
Laravel Sluggable Trait Version 2
<?php
/**
* PHP v7+
* Remember for this to work, in your controller you need to do:
* $model->slug = request('title')
* columns name are: title and slug
*/
namespace App\Traits;
trait Sluggable
{
/**
* Get the Slug instead of id
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
/**
* Slug Mutator
*
* @param $value
*/
public function setSlugAttribute($value)
{
if (static::whereSlug($slug = make_slug($value))->exists()) {
$slug = $this->incrementSlug($slug);
}
$this->attributes['slug'] = $slug;
}
/**
* Increment Slug
*
* @param $slug
* @return mixed|string
*/
public function incrementSlug($slug)
{
$max = static::where('title', $this->title)->latest('id')->value('slug');
if (is_numeric($max[-1])) {
return preg_replace_callback('/(\d+)$/iu', function ($matches) {
return $matches[1] + 1;
}, $max);
}
return "{$slug}-2";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment