Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active December 16, 2021 16:56
Show Gist options
  • Save james2doyle/9f3137f8a3ed7df137b0f035dac58207 to your computer and use it in GitHub Desktop.
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
<?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