Question: Delete/detach first pivot table records

Question

Delete/detach first pivot table records

Answers 1
Added at 2017-01-05 20:01
Tags
Question

Case
Laravel 5.3

Having a pivot table between Cart & Product with an additional column:

id - cart_id - product_id - item_id (additional column)
1  -    1    -     1      -    5
2  -    1    -     1      -    6
3  -    1    -     1      -    7
4  -    2    -     1      -    8

Normally you detach a pivot table record using:
$product->carts()->detach($cartId);

But in this case, there are several pivot table records with the same cart & product id

Problem

Lets say I want delete to row 1.

What I hoped to work was either one of these:
$product->carts()->detach($itemId);
or
$product->carts()->detach($cartId)->first();

If I query the pivot table based on cart_id & product_id, call the first & run delete() on that query result a Call to undefined method stdClass::delete() will be returned

$firstItem = DB::table('cart_product')
  ->where('cart_id', $cart_id)
  ->where('product_id', $product->id)
  ->first();    

$firstItem->delete();

Although when I dd() $firstItem after querying the data, it will return a (correct) object

{#238 ▼
  +"id": 1
  +"cart_id": 1
  +"product_id": 1
  +"item_id": 5
}
Answers to

Delete/detach first pivot table records

nr: #1 dodano: 2017-01-05 20:01

You can't use detach() if you want to delete just one row in this table.

If you want to delete just first item, just use this:

DB::table('cart_product')
  ->where('cart_id', $cart_id)
  ->where('product_id', $product->id)
  ->take(1)
  ->delete();

Or from your code:

$id = DB::table('cart_product')
  ->where('cart_id', $cart_id)
  ->where('product_id', $product->id)
  ->first()->id;

DB::table('cart_product')
  ->where('id', $id)
  ->delete();
Source Show
◀ Wstecz