Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

General error: 1364 Field 'user_id' doesn't have a default value [duplicate]

Tags:

php

laravel

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? enter image description here

like image 268
Mohammed Sabbah Avatar asked Apr 27 '17 07:04

Mohammed Sabbah


3 Answers

you need to change database strict mode. for disable follow below step

  1. Open config/database.php

  2. find 'strict' change the value true to false and try again

like image 179
Shailesh Ladumor Avatar answered Nov 06 '22 17:11

Shailesh Ladumor


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()
]);
like image 33
Mohammed Sabbah Avatar answered Nov 06 '22 15:11

Mohammed Sabbah


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.

like image 27
Lamin Barrow Avatar answered Nov 06 '22 15:11

Lamin Barrow