Mette
Mette

Reputation: 207

LARAVEL - Show products to related category

I'm trying to show products related to the category. In my menu I have a list of categories if I click this category i want to see related products to this category. I'm just learning laravel can somebody help me out..

DATABASE:

 -categories: ID, NAME
 -products: has Category_id

View

Route::get('/category' , [
    'uses' => 'productController@getCategory',
    'as' => 'category.single'
    ]);

Controller

public function getCategory($category) {
    $singleCategory = Category::find($category);
    return view('pages.category', ['category' => $singleCategory]);
}

How do I go from here?

Upvotes: 1

Views: 7577

Answers (3)

Shahaf Antwarg
Shahaf Antwarg

Reputation: 497

in Category.php Model add a relation

public function products()
{
  return $this->hasMany('App\Product');
}

then you can call

$singleCategory->products

and you'll get you products by category_id

Upvotes: 1

rap-2-h
rap-2-h

Reputation: 31948

How do I go from here?

I don't know.

But for your problem, if you want to get the products of a Category just do:

$singleCategory = Category::find($category);
$products = $singleCategory->products;

(I assume you added a products method in your Category model, if not, read this: https://laravel.com/docs/5.4/eloquent-relationships#one-to-many).

Then you can display your products by looping on your products:

foreach($products as $product) { 
     echo $product->name; 
}

Upvotes: 0

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

As per the following lines:

$singleCategory = Category::find($category);
return view('pages.category', ['category' => $singleCategory]);

category list is available on pages.category page under $category. Its a Collection object, you can access its object by using foreach() loop.

Upvotes: 0

Related Questions