Home > database >  Naming Laravel Controllers for displaying products filtered by categories
Naming Laravel Controllers for displaying products filtered by categories

Time:08-10

So my products (books) are filtered into Fiction / Non Fiction, and into subcategories for each, i've made all the logic for filtering and displaying the products but what i'm struggling with is naming the routes and controllers for it.

I thought of using one resource BookController with the standard 7 methods, and somehow passing a criterium, fiction/nonfiction or specific subcategory id into the index method, that then calls my BookService class which returns the proper collection.

I don't think posting my code will be very helpfull but just in case, these are my BookService methods

  /*
   Returns a collection of n random recommended books
   n = $quantity
  */
  public function getRecommended(int $quantity){
    return Book::with('authors')->get()->random($quantity);
  }

  /*
   Returns a collection of books by passed categoryId
  */
  public function getByCategory(int $categoryId){
    return Book::with('authors', 'category')->category($categoryId)->get();
  }

  /*
   Returns a collection of fiction books
  */
  public function getFiction(){
    return Book::with('authors', 'category')->nonFiction()->get();
  }

  /*
   Returns a collection of non fiction books 
  */
  public function getNonFiction(){
    return Book::with('authors', 'category')->fiction()->get();
  }

fiction(), nonfiction(), category($categoryId) are local scopes in my Book Eloquent Model.

My question is

  1. What should I name controllers for displaying All books and Filtered books, and what should i call their methods?
  2. Should i maybe use one BookController resource controller and somehow pass it's index method the criterium for filtering, if that's the proper way, can somebody help me with how to actually pass the criterum from my view with Blade Templates and how to set it up using Route::resource(..).

Thanks in advance.

CodePudding user response:

the laravel generated resources for controllers represents the CRUD functions (create, read, update, delete) if you treat your eloquent models in your application as a resource.

i'm assuming that your problems are more about diplaying the books for your clients (visitors) a READ action.

Laravel doesn't force you to user the default generated crud actions, if you need to create a method that is not in context of model only, for exemple getting the mode data for your book by calling an external ISBN api, it's totally olowed.

So i recommend keeping all your actions in "BookController"

  • if you want to keep the default actions you can do your filtering inside the "index" method.
  • if you want to add a "filter" method and add it in your routes, nothing in laravel is preventring you.

NOTE : for the "getRecommended" method, it's not optimized, you can use Book::with("authrs")->inRandomOrder()->take($quantity)->get();

  • Related