mheonyae
mheonyae

Reputation: 643

Laravel eloquent delete all records which id's are not equal to a list of id's

So i have a table containing active and inactive lessons (at the moment all are labeled as active, i want to delete inactive ones not update). I get a list of all active lessons.

    foreach($lesson->data as $newdata){
        $newdata->id; 
    }

$newdata->id represents id's of still active lessons, so i want to delete all lessons that dont have a id from the above foreach result. Is there a way to build a query?

Something like: ... ->where('l_id', '!=', '$newdata->' )->orWHere('l_id', '!=', '$newdata->' ) ... in this sense kinda. Of in this exact form this wont work.

Upvotes: 1

Views: 1856

Answers (1)

Evandro Lacerda
Evandro Lacerda

Reputation: 238

If you already have a collection and want to delete all but the records that are in this collection you could do something like:

$idsToKeep = $lessons->pluck('id')->toArray();
Lessons::whereNotIn('id', $idsToKeep)->delete();

Before delete some records I recomend backup your data.

Upvotes: 3

Related Questions