Laravel 5 detach() many to many ignores attributes

I’ve a basic many-to-many content-categories table structure.

I’ve 3 tables: content, category and content_category cross table

content_category structure:

  • content_categories.cid => Content id
  • content_categories.tid => Category id
  • content_categories.tag => Boolean

So ive coded my model relationships both on the content_categories table, switching on the tag attribute.

Model

// Relevant code
class Content extends Model {

    public function categories() {
        return $this->belongsToMany('content_categories', 'cid', 'tid')->where('tag', false);
    }

    public function tags() {
        return $this->belongsToMany('content_categories', 'cid', 'tid')->where('tag', true);
    }


}

Repository

// Relevant code
class ContentRepository {
    // Works properly
    function getTags($content) {
        return $content->tags;
    }

    // Works properly
    function addTag($content, $tagId) {
        $content->tags()->attach($tagId);
        return $content;
    }

    // Broken: removes all categories, even these where tag = false
    function deleteTag($content, $tagId) {
        $content->tags()->detach($tagId);
        return $content;
    }
}

Problem is, when i call deleteTags() every relation is dropped, even those with tag = false. What’s wrong here?


Source: laravel

Leave a Reply