Search code examples
phplaraveleloquentormmany-to-many

Get all articles belongs to subcategories ManyToMany Laravel


I'm trying to display all campaigns belongs to a parent category

enter image description here

Category Model :

   public function parents()
    {
        return $this->hasMany('App\Category');
    }


    public function categories()
    {
        return $this->belongsTo('App\Category','id','parent_id','categories');
    }


    public function campaigns()
    {
        return $this->belongsToMany('App\Campaign' );
    }

Campaign Model :

public function categories()
    {
        return $this->belongsToMany('App\Category' , 'campaign_category', 'campaign_id', 'category_id');
    }


Solution

  • Sorry, i just did this :D

        $campaigns = Campaign::whereHas('categories', function($q) use($id) {
            $q->where('parent_id', '=', $id);
        })->get();