Skip to content
Advertisement

How to generate and set username in Laravel eloquent?

I have some fields in user table:

id  firstName  lastName userName

Here I need to generate and save an userName automatically where the user will provide only firstname & lastName. I have tried something like this but not sure about the piece of code.

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;
        });
    }

}

So whenever I’m trying to migrate & seed it’s showing

Field ‘userName’ doesn’t have a default value

The seeder is

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

Advertisement

Answer

What you’re looking for is Model events.

First define a static boot method on your model. In there you can then run your username generation code.

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;
        });
    }
}

This will intercept the creation of your model, and generate the username.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement