0
votes

i have got this error while working with laravel. I am trying to save a book data and save its owner user with user_id. Sorry about question format.

public function store(InfoValid $request)
{
    $request->validated();
    $user = Auth::user()->books()->create($request->except('_token'));
    //dd($user ->user_id);
    Book::create($request->except('_token'));
    redirect("/books");
}
}

"SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into books (name, page, ISBN, price, published_at, updated_at, created_at) values)) ◀"

in my User class i have:

public function books(){
    return $this->hasMany(Book::class);
}

and in my Book class:

protected $fillable = [
    "name" , "page" , "ISBN" , "price" , "published_at"
];

public function user()
{
return $this ->belongsTo(User::class);
}

and in my books table:

$table->unsignedInteger("user_id");

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade')
            ->onUpdate('cascade');

When i dd() the user_id(i have commented that) it gives me the user_id but i don't know why i'm facing this error

1
Are you specifying the value for user_id while you insert (answer is no)? Does the field user_id exist in your table (answer is yes)? What should the value be for the user_id when you don't specify it in the insert? A default value. That wasn't specified while creating the table. So, why do you get that error then? I gave you all the clues, and the error message tells you why also. - N.B.
What the default value should be? i gave defined it nullable but whenever i saved a book actually 2 books(one for null and another fo user_id) were saved. - Saeid Rasouli
Why do you have this line Book::create($request->except('_token'));? You should probably remove it. You've already saved it with books()->create(...). - Paul Spiegel
Oh! thank you. i removed it and it works. I'm new to laravel and php. i saw in a video for another project and didnt notice that! - Saeid Rasouli

1 Answers

0
votes
Auth::user()->books()->create($request->except('_token'));

Will set the user_id in the Book entity automatically.

But here

Book::create($request->except('_token'));

the user_id will not be set. So laravel will try to insert the book without user_id (which is required), and MySQL will complain. But you also don't need that second line, since the book is already saved with the first one.