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
user_idwhile you insert (answer is no)? Does the fielduser_idexist in your table (answer is yes)? What should the value be for theuser_idwhen 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.Book::create($request->except('_token'));? You should probably remove it. You've already saved it withbooks()->create(...). - Paul Spiegel