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

bosborne's avatar

Called 'diff' on Laravel collection, but could have been retrieved as a query

Hi all,

I am running Larastan for static analysis and my code retrieves some results from the database via Eloquent and uses the diff() method to retrieve the items not in the collection passed, it works fine but Larastan reports this error:

Called 'diff' on Laravel collection, but could have been retrieved as a query.

What would be the alternative?

My code:

FlightRoute::all()
            ->diff($routes)
            ->each(fn (FlightRoute $flightRoute) => $flightRoute->delete());
0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Something like this would work with a single query to delete the unwanted records

FlightRoute::whereNotIn('id', $routes->pluck('id'))->delete();

However, this will not trigger any deleted or deleting model events, so you if you need to individually remove those records:

FlightRoute::whereNotIn('id', $routes->pluck('id'))->get()
    ->each(fn (FlightRoute $flightRoute) => $flightRoute->delete());
1 like

Please or to participate in this conversation.