Last active
December 16, 2021 16:56
-
-
Save james2doyle/9f3137f8a3ed7df137b0f035dac58207 to your computer and use it in GitHub Desktop.
A trait for Laravel (v8) that uses model events to set a slug field based on another field
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 | |
namespace App\Traits; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Support\Str; | |
/** | |
* Handles the logic for settings slugs | |
*/ | |
trait HasSlug | |
{ | |
protected static function bootHasSlug(): void | |
{ | |
static::creating(function (Model $model) { | |
$sluggableSeparator = property_exists($model, 'sluggableSeparator') ? $model->sluggableSeparator : '-'; | |
$sluggableAttribute = method_exists($model, 'getSluggableAttribute') ? $model->getSluggableAttribute() : 'name'; | |
$sluggableField = method_exists($model, 'getSluggableField') ? $model->getSluggableField() : 'slug'; | |
// use app container to allow mocking/spying/replacing of the slug call | |
$model->{$sluggableField} = optional($model)->{$sluggableField} ? (string) app(Str::class)->slug($model->{$sluggableField}, $sluggableSeparator) : (string) app(Str::class)->slug($model->{$sluggableAttribute}); | |
}); | |
static::updating(function (Model $model) { | |
$sluggableSeparator = property_exists($model, 'sluggableSeparator') ? $model->sluggableSeparator : '-'; | |
$sluggableAttribute = method_exists($model, 'getSluggableAttribute') ? $model->getSluggableAttribute() : 'name'; | |
$sluggableField = method_exists($model, 'getSluggableField') ? $model->getSluggableField() : 'slug'; | |
// use app container to allow mocking/spying/replacing of the slug call | |
$model->{$sluggableField} = optional($model)->{$sluggableField} ? (string) app(Str::class)->slug($model->{$sluggableField}, $sluggableSeparator) : (string) app(Str::class)->slug($model->{$sluggableAttribute}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment