I'm new to Laravel so I have a bit of a problem. I have tables 'Categories' and 'Products' in my DB. In my models I setup the relations like:
Product.php:
public function category()
{
return $this->belongsToMany(Category::class);
}
Category.php:
public function products()
{
return $this->hasMany(Product::class);
}
What I need now is that I want to select all of the Categories with their related Products. (User enters in search bar category name and gets list of Categories and when user selects Category I get all of the columns from Categories and ALSO Products related with this Category).
I have tried something like this:
public function findCategory(Request $request)
{
return Category::with('products')
->where('name', 'like', '%' . $request->category_name . '%')
->limit(15)
->get();
}
ALSO:
public function findCategory(Request $request)
{
return Category::where('name', 'like', '%' . $request->category_name . '%')
->products()
->limit(15)
->get();
}
But this doesn't seem to work and I ran out of ideas. Does anyone know if there is a way to do this? Any help would be much appreciated :)