Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

KangarooMusiQue's avatar

If i try to delete table-rows with a skip it deletes all rows in the table :(

I try to delete everything from a table except the latest three rows.

So i did:

NextTitle::latest()->skip(3)->delete();

But it deletes the whole Table instead of leaving the latest three. What am i doing wrong? i want to delete everything from the table exept the last three entries.

0 likes
8 replies
jeevamugunthan's avatar

you need to take count of table first and store it into $count and

NextTitle::latest()->take($count)->skip(3)->delete();
KangarooMusiQue's avatar

Thank you. But if i try this i get a

Undefined variable: count

As i am very new to this, i dont know why this happens?!

So i now have set $count to 1 and if there is only one row in the database it works with

    $count=1;
    NextTitle::latest()->take($count)->delete();

But if there is more than one row it deletes just the latest. I think i have to read more about this and watch some more tutorials.

But if someone can explain (i've googled long) this how to delete everything on a table exept the latest three entries. i will be very thankful.

Checked it again. i was wrong it deletes the last entry :( I getting mad.

jeevamugunthan's avatar

you need to get count of your table like

$count=NextTitle::count();
1 like
jeevamugunthan's avatar
Level 2

or try this

NextTitle::latest()->take($count)->skip(3)->get()->each(function($row){ $row->delete();});

1 like
KangarooMusiQue's avatar

@jeevamugunthan i did it like that and it works. Thank you very very much!

    $count = NextTitle::count();
    NextTitle::latest()->take($count)->skip(3)->get()->each(function($row){ $row->delete();});
1 like
jeevamugunthan's avatar

you need to delete all rows without latest 3 rows right then how u set $count=1 its not right, so you need to take total table count the count is must be atleast 4

1 like
KangarooMusiQue's avatar

I think the way to skip(3) is much better but i even dont know why it did not work at the first try. Will test more. I'm happy it works now, but have to try some more, now if i know how it works :-)

Snapey's avatar

get the IDs of the top 3 rows then delete all others rows whereNotIn

$safe = NextTitle::latest()->take(3)->get('id')->toArray();

NextTitle::whereNotIn($safe)->delete();

Don't just assume that IDs are consecutive and complete

Please or to participate in this conversation.