How to get many to many relationship items in laravel How to get many to many relationship items in laravel laravel laravel

How to get many to many relationship items in laravel


Assuming Laravel Model classes - Series, Category and Product

For the Series Model Class, create a function

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

For the Category Model Class, create a function

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

Now for a given Series, you can easily retrieve all related categories using thesimple function call

$categories = $series->categories();

Finally coming to the main problem of showing products under multiple categories.

for($categories as $category){     $productsOfThisCategory = $categories->products();     //save into some other data structure, say an array $allProducts}

$allProducts will have multi-category products for a specific Series.

Refer : Standard eloquent relationship -Many to Many


If I understand you correctly, then your models looks like below

class Series extends Model{    // other code    public function categories() {        return $this->belongsToMany('App\Category');    }    // other code}class Category extends Model{    // other code    public function series() {        return $this->belongsToMany('App\Series');    }    public function products() {        return $this->belongsToMany('App\Product');    }    // other code}class Product extends Model{    // other code    public function categories() {        return $this->belongsToMany('App\Category');    }    // other code}

Further to get all products of certain series you need to do so

public function view($series = 0, $cat = 0, $page = 1){    if (!empty($series)) {        $seria = Series::with(['categories' => function($query) {            $query->with('products');        })->find($series);        // or may be this will work, don't know        // Series::with('categories.products')->find($series);        // get all caegories from seria or certain one        if (empty($cat)) {            $categories = $seria->categories;         }        else {            $categories = $seria->categories()->where('id', $cat)->get;         }        // retrieve produts form each category and making from them collection        $products = $categories->map(function($category) {            return $category->products;        })->flatten();        // or use this approach if above not working        /*$products = collect([]);        foreach ($categories as $category) {            $produts = $products->merge($category->products);        }*/        // do your magic    }    else {        // not exactly understand what you want to do when $series is not set    }    // do your magic}