Home > Blockchain >  How to insert to database user with default value?
How to insert to database user with default value?

Time:01-15

I want to register user and I have 3 fields in form; login, password and confirm_password. In database I have column login, password and role. So I want to insert database user which have default role User. This oode below show me error SQLSTATE[HY000]: General error: 1364 Field 'role' doesn't have a default value. How can I resolve this problem ?

controller

protected function validator(array $data)
{
    return Validator::make($data, [
        'login' => ['required', 'string', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

protected function create(array $data)
{
    $user = User::create([
        'login' => $data['login'],
        'password' => Hash::make($data['password']),
    ]);
    $user->assignRole('role');
    return $user;
}

model

protected $fillable = [
    'login',
    'password',
    'role',
];

migration

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('login');
        $table->string('password');
        $table->string('role')->default('User');
        $table->timestamps();
    });
}

CodePudding user response:

You need to add/modify the Role column with your SQL Client, chances are you have not defined a default value to it, and the column is a "Not Null" one meaning you can't insert a row if this column is empty.

Another option is to have something like that with your create function :

$user = User::create([
    'login' => $data['login'],
    'password' => Hash::make($data['password']),
    'role' => "User"
]);

CodePudding user response:

If you create users only with role "User" you can add this line when you create user;

    protected function create(array $data)
    {
        $user = User::create([
            'login' => $data['login'],
            'password' => Hash::make($data['password']),
            'role'=>"User"
        ]);
        $user->assignRole('role');
        return $user;
}

Or you can use Observer:

class UserObserver
{
    /**
     * Handle the "User" created event.
     *
     * @param User $user
     * @return void
     */
    public function creating(User $user)
    {
        if (is_null($user->role)) {
            $user->role= "User";
            $user->save();
        }
    }
}
  • Related