laravel模型中具有随机值的默认属性

时间:2019-01-04 17:20:16

标签: php laravel laravel-5.7

在laravel项目中,我想为每个新创建的记录设置一个随机的默认值。

根据this Doc,我尝试这样做:

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
    protected $fillable = [
       'access_token'
    ];

    protected $attributes = [
        'access_token' => str::uuid()
    ];
}

但是我在protected $attributes行中遇到了错误

"Constant expression contains invalid operations"

3 个答案:

答案 0 :(得分:1)

这是因为属性不能包含无法在编译时求值的表达式。来自官方documentation

  

类成员变量称为“属性”。您可能还会看到它们   使用其他术语(例如“属性”或“字段”)进行引用,但   就本参考而言,我们将使用“属性”。他们是   使用关键字public,protected或private之一定义,   然后是普通的变量声明。该声明可能   包括一个初始化,但是这个初始化必须是一个常量   值-也就是说,必须能够在编译时进行评估,并且   不得依赖运行时信息进行评估。

另一种方法是通过model events。在用户模型的boot()方法中,您可以加入Creating事件。如果此方法不存在,请创建它。

public function boot()
{
    parent::boot();

    static::creating(function($user) {
        $user->access_token = (string) Str::uuid();
    });
}

答案 1 :(得分:0)

问题是由调用uuid函数的方式引起的。

由于它是静态的,因此您需要使用;

Str::uuid()

这将返回一个对象,因此为了从中获取字符串,您将必须强制转换结果。

(string) Str::uuid()

因此,本质上,您的attribute属性应该是;

protected $attributes = [
    'access_token' => (string) Str::uuid()
];

您可以看看docs

答案 2 :(得分:0)

protected $attributes = [
    'access_token' => ''
];

public function __construct(array $attributes = [])
{
    parent::__construct($attributes);
    $this->attributes['access_token'] = Str::uuid();
}

在php中,不可能从属性中调用函数