Search code examples
phplaravelcruddatabase-migrationlaravel-controller

SQLSTATE[HY000]: General error: 1364 Field 'firstname' doesn't have a default value (SQL: insert into `users` (`email`) values ([email protected]))


I am new to Laravel framework.

I am facing an issue, with migration of User table.I added nullable to 'firstname' of my table, which works but displaying the same error for 'lastname'column. I have included nullable() to every column, which is not the right way to do it. How to solve this?? Can anyone please suggest.

User migration table, facing issue with the 'firstname' column. create_user_table.php

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('firstname');
        $table->string('lastname');
        $table->string('email')->unique();
        $table->date('dob');
        $table->char('address',100);
        $table->bigInteger('phonenumber');
    });
}

UserController with store UserController.php

    public function store(Request $request)
        {
            $request->validate([
                'firstname'=>'required',
                'lastname'=>'required',
                'email'=>'required',
            ]);

            $user=new User([
                $user->firstname=>$request->get('firstname'),
                'lastname'=>$request->get('lastname'),
                'email'=>$request->get('email'),
                'dob'=>$request->get('dob'),
                'address'=>$request->get('address'),
                'phonenumber'=>$request->get('phonenumber')
                ]);
                $user->save();
                return redirect('/users')->with('success','user added');
        }

Solution

  • The easiest way to achieve this is:

       public function store(Request $request)
        {
            $request->validate([
                'firstname'=>'required',
                'lastname'=>'required',
                'email'=>'required',
            ]);
    
                $user=new User();
                $user->firstname = $request->firstname;
                $user->lastname = $request->lastname;
                $user->email = $request->email;
                $user->dob = $request->dob;
                $user->address = $request->address;
                $user->phonenumber = $request->phonenumber;
                $user->save();
                return redirect('/users')->with('success','user added');
        }
    

    Also in your model, you have to add this line for mass assignment

    protected $fillable = ['firstname','lastname','email','dob','address','phonenumber'];
    

    You may check out this link for mass assignment: https://laravel.com/docs/7.x/eloquent#mass-assignment