Level 60
$category = Category::where('slug',$categorySlug)->first();
$products = $category->products
I have categories table and products table in the categories table, I have id/name/slug in products I have id/category_id/name/price
In my URL I have a category slug. now I want to find product from products tables based on this category user has clicked.
I did in this way
public function findProductBasedOnCategory($categorySlug)
{
//first finding category based on slug matched
$category = Category::where('slug',$categorySlug)->first();
$categoryId = $category->id;
//based on category id ,find products from products table
$products = Product::where('category_id',$categoryId)->get();
return view('product.category',compact('products'));
}
How can I do this easily with realtionship
class Category extends Model
{
public function getRouteKeyName()
{
return 'slug';
}
}
Route::get(
'/categories/{category}/products',
'CategoriesController@findProductBasedOnCategory'
);
// ..
public function findProductBasedOnCategory(Category $category)
{
$products = $category->products
return view('product.category',compact('products'));
}
Please or to participate in this conversation.