When I want to add user_id to
carts
Cannot add or update a child row: a foreign key constraint fails (`armytag`.`carts`, CONSTRAINT `carts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))
public function cart()
{
return $this->belongsTo('App\Cart');
}
public function user()
{
return $this->belongsTo('App\User');
}
CartController
public function add(Request $request, $id)
{
$cart = new Cart();
$product = Product::where('id', $id)->first();
$user_id = Auth::user()->id;
$cart->user_id = $user_id;
$cart->product_id = $product->id;
$cart->quantity = $request->quantity;
$cart->create();
return redirect()->back();
}
Cart.php
protected $fillable = [
'user_id', 'product_id', 'quantity'
];
at Connection->runQueryCallback('insert into `carts` (`updated_at`, `created_at`) values (?, ?)'
Firstly, you've defined the cart() relation incorrectly in your User model. User is the owning side of one-to-many relation so you should call hasMany() instead of belongsTo():
public function carts()
{
return $this->hasMany('App\Cart');
}
Secondly, you need to call $cart->save() instead of $cart->create(). save() will save the existing object, while create() will create a new one with values passed as parameters and save it. As no arguments are passed to create(), no values other than timestamps are set in the query.
You can also simplify your code and do just:
public function add(Request $request, $id)
{
Cart::create([
'user_id' => Auth::id(),
'product_id' => $id,
'quantity' => $request->quantity
]);
return redirect()->back();
}