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
Route::resource(..)
.Thanks in advance.
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"
NOTE : for the "getRecommended" method, it's not optimized, you can use Book::with("authrs")->inRandomOrder()->take($quantity)->get();