The post you have mentioned is a proposed idea. We will add class resolving in a future build, so it is possible to replace model instances generally in the backend and other areas. However, it can create a black box, which we want to avoid, so it is best to only recommend it in rare cases.
In this case, you simply want to slug an attribute, which is a simple task, done using events.
// Slug 'slug' attribute from 'name' attribute
User::extend(function($model) {
$model->bindEvent('model.saveInternal', function () use ($model) {
if (!$model->slug) {
$model->slug = Str::slug($model->name);
}
});
});
For a more detailed approach, see the ExtendUserPlugin class in the UserPlus plugin. Implemented in the boot() method with this call:
The problem using Str::slug is that it can create doublette slugs, for example for “Name” and “Name_”. The sluggable trait did this a lot better with adding “name-2” for a second identical name.
So I tried to create sluggable as a Behavior, but I cant get it to work:
class Sluggable extends ModelBehavior
{
use Sluggable;
protected $model;
public function __construct($model)
{
parent::__construct($model);
$this->model = $model;
}
public function updateSlug(): void
{
$this->model->slugAttributes();
}
}
But whatever I do, if I call updateSlug(), the slug attributes are missing and it does not work.