Laravel-如何从特征引导中调用函数

时间:2019-04-12 04:59:33

标签: php laravel traits

我只是创建一个特质来为模型生成弹头

<?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';
    }
}

1 个答案:

答案 0 :(得分:0)

该事件接收模型的实例,因此您可以在该实例上调用方法:

    public static function bootSlugGenerator()
    {
        static::creating(function ($model) {
            $model->slug = $model->slugGenerator();
        });
    }

文档:https://laravel.com/docs/5.8/eloquent#events