Skip to content

Instantly share code, notes, and snippets.

@logaretm
Created January 2, 2017 06:53
Show Gist options
  • Save logaretm/fa7bd58b1ae8adcb9d102cc7a6ba3518 to your computer and use it in GitHub Desktop.
Save logaretm/fa7bd58b1ae8adcb9d102cc7a6ba3518 to your computer and use it in GitHub Desktop.
Fills the slug column automatically for the models using this trait.
<?php
namespace App\Traits;
trait Sluggable
{
/**
* Boots the sluggable trait.
*/
public static function bootSluggable()
{
static::saving(function ($model) {
if (! $model->exists) {
$model->slug = str_slug($model->{$model->getSluggableSource()});
}
});
}
/**
* @return string
*/
protected function getSluggableSource()
{
if (property_exists($this, "sluggableSource")) {
return $this->{"sluggableSource"};
}
return "name";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment