Created
January 2, 2017 06:53
-
-
Save logaretm/fa7bd58b1ae8adcb9d102cc7a6ba3518 to your computer and use it in GitHub Desktop.
Fills the slug column automatically for the models using this trait.
This file contains hidden or 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\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