Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 - Deleting specific records from the pivot table

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.

like image 940
Sérgio Nader Avatar asked Aug 27 '17 18:08

Sérgio Nader


1 Answers

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);
like image 95
jaysingkar Avatar answered Oct 23 '22 11:10

jaysingkar