labas GamePage visogero labas GamePage visogero - 4 months ago 19x
PHP Question

Can't insert user_id and product_id to cart. Laravel 5

When I want to add user_id to

I get this error

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`))

The migration went well without this error. I'm using Laravel 5. This is my User.php function:

public function cart()
return $this->belongsTo('App\Cart');

This is Cart.php function:

public function user()
return $this->belongsTo('App\User');

This is the function in

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;
return redirect()->back();

I've also set fillable fields in my

protected $fillable = [
'user_id', 'product_id', 'quantity'

Also I get this line in the error log:

at Connection->runQueryCallback('insert into `carts` (`updated_at`, `created_at`) values (?, ?)'

It seems that it is not even trying to insert user_id and product_id


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)
      'user_id' => Auth::id(),
      'product_id' => $id,
      'quantity' => $request->quantity

    return redirect()->back();