I am trying to assign the user_id with the current user but it give me this error
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a
default value (SQL: insert into `posts` (`updated_at`, `created_at`)
values (2017-04-27 10:29:59, 2017-04-27 10:29:59))
here is my method
//PostController
Post::create(request([
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]));
with these fillables
//Post Model
protected $fillable = ['title', 'body', 'user_id']
However this method do the job
//PostController
auth()->user()->publish(new Post(request(['title' ,'body'])));
//Post Model
public function publish(Post $post)
{
$this->posts()->save($post);
}
any idea why this fail?
you need to change database strict mode. for disable follow below step
Open config/database.php
find 'strict'
change the value true to false and try again
So, after After reviewing the code again, I found the error. I am wondering how no one notice that! In the above code I wrote
Post::create(request([ // <= the error is Here!!!
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]));
actually, there is no need for the request function warping the body of the create function.
// this is right
Post::create([
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]);
I've had a similar issue with User registration today and I was getting a
SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value (SQL: insert into users
I fixed it by adding password
to my protected $fillable array and it worked
protected $fillable = [
'name',
'email',
'password',
];
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With