skip to Main Content

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 ?

3

Answers


  1. 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"
    ]);
    
    Login or Signup to reply.
  2. 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();
            }
        }
    }
    
    Login or Signup to reply.
  3. Controller Logic:

    $user = User::create([
            'login' => $request->login,
            'password' => Hash::make($request->password)]);
    

    Model Logic if you want to insert default value

    class User extends Model
    {
        
        public static function boot()
        {
            parent::boot();
            self::creating(function ($model) {
                $model->role='user';
            });
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search