Laravel 5.4 - Deleting specific records from the pivot table

Sérgio Nader picture Sérgio Nader · Aug 27, 2017 · Viewed 7.7k times · Source

For each visit I may have many products; therefore the pivot table (product_visit) has the fields: id, product_id, visit_id, qtd and amount.

To delete a visit and its related records on the pivot table, everything works fine:

 public function getVisitDelete($id){
    $visits = Visit::find($id);
    $visits->products()->detach();
    $visits->delete();
}

However, I could not figure out how to delete one specific record from the pivot table using detach or something similar. So I ended up doing the following:

public function getProductVisitDelete(){
    $visit_id   =   (int)Request('visit_id');
    $product_id =   (int)Request('product_id');
    $sqlDelete = "delete from product_visit where visit_id=$visit_id and product_id = $product_id";
    DB::select($sqlDelete);
}

Though it works, I am far being happy with this solution -- looks like I am missing something.

Answer

jaysingkar picture jaysingkar · Aug 27, 2017

You can use wherePivot() method to detach specific product from the visit.

$visits = Visit::find($visit_id);
$visits->products()->wherePivot('product_id','=',$product_id)->detach();

Update As given in Laravel docs "Attaching / Detaching" section, you can pass the related model's id that you want to remove in detach() method. Example

$visits = Visit::find($id);
$visits->products()->detach($product_id);