How to delete multiple entries using Laravel Eloquent

Now, from what I see, it should have been simple.

I want to delete several records from the database. I have idall the entries that I want to delete. I call the route resource.destroyusing a comma separated list of identifiers (of idtype postgres uuid), for example:

Request URL:http://foo.app/products/62100dd6-7ecf-4870-aa79-4b132e60c904,c4b369f1-d1ef-4aa2-b4df-b9bc300a4ff5
Request Method:DELETE

On the other hand, my controller action looks like this:

public function destroy($id)
{
    try {
        $ids = explode(",", $id);
        $org->products()->find($ids)->delete();
    }
    catch(...) {
    }
}

This gives me the following error:

BadMethodCallException in Macroable.php line 81:
Method delete does not exist.

in Macroable.php line 81
at Collection->__call('delete', array()) in ProductsController.php line 251
at Collection->delete() in ProductsController.php line 251
at ProductsController->destroy('62100dd6-7ecf-4870-aa79-4b132e60c904,c4b369f1-d1ef-4aa2-b4df-b9bc300a4ff5')

I checked that it find()returns a collection productsmatching the specified identifiers.

What am I missing?

PS: 1. The model Producthas several relationships belongsTowith other models. 2. The code product.destroyworks fine if I pass it to him aloneid

, , :

$org->products()->find($ids)->delete()

$org->products()->whereIn('id', $ids)->get()->delete()

? , , find, get Collections

+4
3

, delete() , .

.

deleting/deleted, , , .

destroy , . , delete(). , , destroy().

public function destroy($id)
{
    try {
        $ids = explode(",", $id);
        // intersect the product ids for the org with those passed in
        $orgIds = array_intersect($org->products()->lists('id'), $ids);
        // now this will only destroy ids associated with the org
        \App\Product::destroy($orgIds);
    }
    catch(...) {
    }
}

, delete() . foreach, each :

public function destroy($id)
{
    try {
        $ids = explode(",", $id);
        $org->products()->find($ids)->each(function ($product, $key) {
            $product->delete();
        });
    }
    catch(...) {
    }
}

, - , , . delete() , - . , :

public function destroy($id)
{
    try {
        $ids = explode(",", $id);
        // call delete on the query builder (no get())
        $org->products()->whereIn('id', $ids)->delete();
    }
    catch(...) {
    }
}
+10

. $orgs . , :

foreach($orgs as $org) 
{
    $org->delete();
}
0

find, . whereIn

public function destroy($id)
{
    try {
        $ids = explode(",", $id);
        $org->products()->whereIn('id', $ids)->get()->delete(); 
    }
    catch(...) {
    }
}

.

-2

Source: https://habr.com/ru/post/1626244/


All Articles