Я создаю API для магазина. У меня проблема с корзиной с этой ошибкой.
Миграция-
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->integer('product_id');
$table->integer('quantity');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('carts')->onDelete('cascade');
});
}
Модель-
protected $fillable = ['user_id', 'product_id', 'quantity'];
public function user() {
return $this->belongsTo('App\User');
}
Контроллер-
public function store(Request $request)
{
// user logged in id
$user_id = auth()->user()->id;
// product id
$product_id = $request->product_id;
// find if item exists in cart.
$cart = User::findOrFail($user_id)->carts()->where('product_id', $product_id)->first();
if ($cart != null) {
// if exists, increment quantity
$cart->quantity = $cart->quantity + 1;
// save modal
$cart->save();
} else {
// create a new cart product.
$cart = Cart::create(['user_id' => $user_id, 'product_id' => $product_id, 'quantity' => 1]);
}
// return all products
return $this->index();
}
Странно, но иногда я могу сохранять данные в корзинах (обычно в первый раз).
Затем я получаю это ошибка .
Спасибо!