jeudi 2 juin 2016

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

When I want to add user_id to carts 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 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();
}

I've also set fillable fields in my Cart.php

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire