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

psychomantis101's avatar

Delete all records except latest 1000

I wish to limit the number of records in a table of my database to a 1000. (keeping the newest 1000). I'm sorry I don't have any code to show, I really had no clue how to do it at all.

0 likes
5 replies
mdeorue's avatar

In my opinion you want to use skip. Something like this.

DB::table('table')->latest()->skip(1000)->delete();

1 like
psychomantis101's avatar

Thanks for pointing me in the right direction with skip. Although there are 2 bugs in the code you provided (at least for mysql); I will point them out for others stumbling across this question.

  1. You can't use skip without a take
  2. You cant delete with a skip/take (some mysql limitation)

Unfortunately these 2 limitations made me use 2 queries and a loop! I'm sure there is a better way of doing this.

$count = Table::count();

$deleteUs = Table::latest()->take($count)->skip(1000)->get();

foreach($deleteUs as $deleteMe){
            Table::where('id',$deleteMe->id)->delete();
        }
psychomantis101's avatar

Slightly improved version. Removes query from loop.

$ids = [];
$count = Table::count();

$deleteUs = Table::latest()->take($count)->skip(1000)->get();

foreach($deleteUs as $deleteMe){
            $ids[] = $deleteMe->id;
        }

Table::destroy($ids);
1 like
mdeorue's avatar
mdeorue
Best Answer
Level 6

Or maybe this.

$deleteUs = Table::latest()->take($count)->skip(1000)->get()->each(function($row){ $row->delete(); });

2 likes
Snapey's avatar

is 1000 fixed number or is approximate ok? I'm just thinking that with deleted records, this might not work exactly

if you are using auto incrementing ids

    $top = Model::latest()->pluck('id');

    Model::latest()->where('id', '<', $top-1000)->delete();

Make sure you test it on some unwanted data!

Basically, find the highest ID then delete everything with an ID that is less than the current ID minus 1000 (without looping over the entire set)

Please or to participate in this conversation.