简体   繁体   中英

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?

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.

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; 
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM