david001's avatar

How to do this with relationship

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

0 likes
3 replies
Sergiu17's avatar
$category = Category::where('slug',$categorySlug)->first();

$products = $category->products
Sergiu17's avatar
Sergiu17
Best Answer
Level 60
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'));
}
david001's avatar

Thank you. One more step is to include this relationship in Category.php



 public function products()
   {
       return $this->hasMany(Product::class);
   }
1 like

Please or to participate in this conversation.