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

RomainB's avatar
Level 13

Using withCount('a')->having('a_count', '=', 0)->delete() erase all the table!

Hi.

I've got an issue which is pretty weird. I have two models with ManyToMany relationship: Website and Keyword.

I'm using KeywordController@destroy to "detach" the relation from the Website model, then I want to delete unused Keywords from the database.

I would use:

public function destroy(Website $website, Request $request)
{
    $website->keywords()->detach($request->all()); // IDs are passed as an array [1, 2, 3]

    Keyword::withCount('websites')
        ->having('websites_count','=', 0)
        ->get(); // Works as expected, returns just some rows

    Keyword::withCount('websites')
        ->having('websites_count','=', 0)
        ->delete(); // DELETE all rows from the table!
}

The problem is Laravel just performs a "DELETE FROM keywords" (seen in Telescope) so the table is just like truncated (except that the primary key isn't reinitialized).

What is weird is when I do the same query with get() instead of delete(), I get what I expect: just some rows, not the entire table!

Why?

0 likes
3 replies
Nakov's avatar
Nakov
Best Answer
Level 73

@romainb yeah, that's a really weird behavior, I reproduced it on my table as well.. This is what worked for me, and it is simplified.

Keyword::doesntHave('websites')->delete(); 

I think that problem has to do by running having() on the query, but I am not sure..

Let me know if this works for you :)

RomainB's avatar
Level 13

@nakov It works as expected! Thanks. There are so many helpers in Laravel... I didn't know this one.

@jlrdw The SQL is really "DELETE from Keywords" - I looked in telescope

I tried something else to understand what causes that, I think it's having too:

Keyword::withCount('websites')
            ->having('websites_count','=', 1)
            ->delete();

It also deletes all the rows from the table...

Please or to participate in this conversation.