我只是创建一个特质来为模型生成弹头
<?php
namespace App\Traits;
trait SlugGenerator
{
public function slugGenerator($slug = null)
{
return $slug ?? 'UUIDGeneratorFunction';
}
public static function bootSlugGenerator()
{
static::creating(function ($model) {
// How to call slugGenerator() function here?
$model->slug = slugGenerator();
});
}
}
问题是:如何在特征启动中调用slugGenerator()
函数?
如果我想从任何模型中更改Slug Generator,我设置$slug
变量的方式是否正确?示例:
<?php
namespace App\Models;
use App\Traits\SlugGenerator;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use SlugGenerator;
public function slugGenerator($slug = null)
{
return 'customSlug';
}
}
答案 0 :(得分:0)
该事件接收模型的实例,因此您可以在该实例上调用方法:
public static function bootSlugGenerator()
{
static::creating(function ($model) {
$model->slug = $model->slugGenerator();
});
}