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

andrecuellar's avatar

How to delete data from relation

Hello, I have 3 tables. locations (Location model) categories (Category model) location_category (hasn't model)

in the Location model, I have the "categories" function

public function categories()
{
    return $this->belongsToMany(Category::class, 'location_category', 'location_id', 'category_id')
        ->withPivot('category_name', 'primary_category')
        ->withTimestamps();
}

in the Category model, I have the "locations" function

public function locations()
{
    return $this->belongsToMany(Location::class, 'location_category', 'category_id', 'location_id')
        ->withPivot('category_name', 'primary_category')
        ->withTimestamps();
}

I want to delete location_category data where 'location_id' column = $locationId. How can I delete that if I know that the "location_category" table hasn't model?

0 likes
5 replies
andrecuellar's avatar

If I use detach, Is the data removed from the database? Or should it be removed? It was not very clear to me. Sorry

MichalOravec's avatar

The detach method will delete the appropriate record out of the intermediate table; however, both models will remain in the database.

What from that isn't clear?

1 like
andrecuellar's avatar

Thanks for your help, I had a "No query results for model [App\Location]" problem because I want to apply it on a seeder whose data from my table is removed with softdeletes (). However, in data that has not been erased with softdeletes, it works correctly, Is it possible to do it with columns where "deleted_at" are non-null? It is a seeder to clean data

Please or to participate in this conversation.