0

Let's assume we have the following two Models: CategoryModel (hasMany ProductModel) and a ProductModel.

Now the user navigates to the route /categories and sees a list of the categories (CategoryController::index()). The user can now click on a category to see the products in this category.

Would you place this logic into the CategoryController? In a function called details or something similar (CategoryController::details($categoryId)) or would the logic, to show the products for a category move to a ProductController::index($categoryId)?

rakete
  • 2,953
  • 11
  • 54
  • 108

2 Answers2

1

It's true that user clicks on the category however you are going to have interaction with ProductModel and you will probably write code like this:

public function index(){
  $products=ProductModel::query();
  if($categoryId=\request('category_id')){
  $products->where('category_id',$categoryId);
  }
   $data=[
    "products"=>$products->get();
   ];
   return view("products.index",$data);
}

As you can see our main Model in the code above is ProductModel and the view we are returning refers to products directory. So you should put your code in the ProductsController

By the way if you want to make your code clean you can use laravel model scope and your code will be changed to:

public function index(){

 $data=[
  "products"=>ProductModel::filter()->get();
  ];
  return view("products.index",$data);
}

All the filtering scripts will be behind the filter scope

Tohid Dadashnezhad
  • 1,808
  • 1
  • 17
  • 27
1

IMHO I would go for a /categories/{category}/products route pointing to a CategoryController::products($categoryId) function.

Going to a filtered /products index is less clear to me, it could generate confusion with the products REST routes.

You can also check in the Laravel documentation for nested resources.

dparoli
  • 8,891
  • 1
  • 30
  • 38
  • It's another way you use and it's cool. But don't forget that in this case you make two database queries one for getting Category and the other one for getting the Category's children. – Tohid Dadashnezhad Feb 16 '19 at 18:25
  • 1
    You can load related models with a join. What I tried to explain is the accepted way to handles resourceful REST soubroutes, you can see also [here](https://stackoverflow.com/questions/20951419/what-are-best-practices-for-rest-nested-resources) or the Rails documentations for subroutes. – dparoli Feb 16 '19 at 18:29