Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Delete all except latest 5

Tags:

php

laravel

I'm trying to make this query work:

$deleteSubmissions = ViewedSubmission::where('user_id', Auth::user()->id)
    ->latest()
    ->skip(5)
    ->delete();

I want to delete all ViewedSubmissions records for the auth user EXCEPT for the latest 5. How can I make this work? Currently this doesn't delete anything, despite having more than 5 records.

like image 883
Felix Maxime Avatar asked Sep 18 '25 00:09

Felix Maxime


1 Answers

I'd handle it this way:

$keep = ViewedSubmission::where('user_id', Auth::user()->id)
    ->latest()
    ->take(5)
    ->pluck('id');

ViewedSubmission::where('user_id', Auth::user()->id)
    ->whereNotIn('id', $keep)
    ->delete();
like image 60
ceejayoz Avatar answered Sep 20 '25 15:09

ceejayoz