SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value (SQL: insert into users
(email
, firstname
, lastname
, updated_at
, created_at
)
You are getting this error because the default create_users_table
migration doesn't provide default value to the password
field or allow null as value.
when you call
User::create($request->all());
laravel perform an insert query to the database and because the password
is not set, MySQL will return the `SQLSTATE[HY000]
You can solve that by modifying the create_users_table
migration which came by default with a new created laravel project,
Schema::create('users', function (Blueprint $table) {
$table->string('password')->nullable();
$table->string('password')->default("");
});
this will allow you to create new User without provide a password and that column will be set to "" or left empty depending with the method you use to modify the migration like I suggest
Secondly defyning the setPasswordAttribute
on your model doesn't means when you create a new user without password it will set automaticaly a password on that, you can do that by catching the creating
event before inserting the user in the database.
to do that add this in you EventServiceProvider
class EventServiceProvider extends ServiceProvider
{
public function boot()
{
parent::boot();
User::creating(function($user){
if($user->password === "" || empty($user->password)){
$user->password = bcrypt(str_random(10));;
}
})
}
}
this event is trigger before the user is persiste in the database, and that will allow you to make some modification on all attributes that are allready set on the user you want to persiste in the database