Osman Rafi
Osman Rafi

Reputation: 1046

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' => '[email protected]',
            'password' => Hash::make('password'),
           
        ]);
 }

Upvotes: 0

Views: 621

Answers (2)

Linus Juhlin
Linus Juhlin

Reputation: 1273

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.

Upvotes: 1

ali ajouz
ali ajouz

Reputation: 56

setUserNameAttributes function only works when you set username to model, not works automatically

you need to define setFirstNameAttribute function and inside it generate your username

Note: last word in function name is Attribute not Attributes*

Upvotes: 0

Related Questions