user782104 user782104 - 5 months ago 28
PHP Question

How to get many to many relationship items in laravel

There is a data structure for a e-shop:

Series -> (many to many) -> categories -> (many to many) -> products


For example, series is "Outdoor Series" , categories is "t-shirt" , products are "t-shirt A, t-shirt B, etc... "

And here is the controller that list out products in one category

public function view($series = 0, $cat = 0, $page = 1) {
$category = Category::find($cat);

$totalItems = count($category->product);
$itemsPerPage = 30;
$currentPage = $page;
$urlPattern = "/ums/product/view/$series/$cat/(:num)";

$this->data['product_list'] = $category->product()->orderBy('created_at', 'desc')->skip(($page - 1) * $itemsPerPage)->take($itemsPerPage)->get();
$this->data['paginator'] = new Paginator($totalItems, $itemsPerPage, $currentPage, $urlPattern);
$this->data['category'] = $category;
$this->data['page'] = $page;
return view('product/list')->with($this->data);
}


Now, the problem is , I would like to rewrite the code so that instead of showing one category, I would like to show one series as well.

That means if the $series = 0 , then it shows products in one category, if the $cat = 0, then it shows products in multi category

In laravel how to get the products in multi category? try $series->category->product() but no luck, also how to rewrite that function to support showing of the series?

Thanks a lot.

Answer

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 the simple 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