如何在 Laravel eloquent 中生成和设置用户名?

How to generate and set username in Laravel eloquent?

我在用户table中有一些字段:

id  firstName  lastName userName

这里我需要自动生成并保存一个用户名,用户只需要提供名字和姓氏。我试过类似的东西,但不确定这段代码。

User.php

class User extends Authenticatable{
...

protected $appends = ['firstName', 'lastName', 'userName'];

protected $attributes = ['userName' => 'default'];

 public static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub

        self::creating(function ($model) {
            $randNum = rand(10, 99);
            $userName = $model['firstName'] . $model['lastName'] . $randNum;
            $model->userName = $userName;
        });
    }

}

因此,每当我尝试迁移和播种时,它都会显示

Field 'userName' doesn't have a default value

播种机是

 public function run()
 {
        DB::table('users')->insert([
            'firstName' => 'Osman',
            'sureName' => 'Rafi',
            'email' => 'rafi.ogchy@gmail.com',
            'password' => Hash::make('password'),
           
        ]);
 }

setUserNameAttributes功能仅在用户名设置为model时生效,不会自动生效

您需要定义 setFirstNameAttribute 函数并在其中生成您的用户名

注意:函数名的最后一个词是 Attribute 而不是 Attributes*

您要查找的是Model events

首先在您的模型上定义一个静态启动方法。在那里你可以 运行 你的用户名生成代码。

class User extends Model 
{
    public static function boot()
    {
        parent::boot();

        self::creating(function($model){
            $randNum = rand(10, 99);
            $userName = $model['firstName'] . $model['lastName'] . $randNum;
            $model['userName'] = $userName;
        });
    }
}

这将拦截模型的创建,并生成用户名。