towhid's avatar

SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into `posts` (`title`, `body`, `cover_image`, `user_id`, `updated_at`, `created_at`) values (country, this is test country, C:\xampp\tmp\php9C8E.tmp, 2, 201

When i am using this code my controller

        $post=new Post;
        $post->category_id = $request->input('category_id');
        $post->title = $request->input('title');
        $post->body = $request->input('body'); 
        $post->cover_image = $fileNameToStore;
        $post->user_id = Auth()->id();
        $post->save();

this is model code

    public function posts(){
        return $this->hasMany(Post::class);
    }

# then everything is fine my post all show index  but when i am  trying this way 

> this is my post controller code for store
    Auth()->user()->publish(
        new Post(request(['title','body','cover_image']))
    );
### this is model code
public function posts(){
    return $this->hasMany(Post::class);
}

public function publish(Post $post){
    $this->posts()->save($post);

}

## i am following 19.Associating With Users Part 2 jeffry Video but when i trying this code then show this error  i am facing problem ... 

> SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into `posts` (`title`, `body`, `cover_image`, `user_id`, `updated_at`, `created_at`) values (country, this is test country, C:\xampp\tmp\php9C8E.tmp, 2, 2018-04-29 10:37:31, 2018-04-29 10:37:31))

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

The error tells you. You create a post without specifying the category and the field is not nullable and does not have a default value

1 like
towhid's avatar

@Snapey yes its work now :) this was my mistake - Thank you

Auth()->user()->publish(
            new Post(request(['title','body','cover_image','user_id','category_id']))
        );

Please or to participate in this conversation.