我需要在某个子类别下显示所有产品。我已在主页上设置了一个类别菜单,其中显示了所有父类及其子类别。当我点击子类别时,它会将我带到子类别页面,其ID在URL中列出。问题我有,我不知道如何在该页面上显示该子类别下的所有产品?
以下是显示子类别页面的路线:
Route::group(['middleware' => ['web']], function () {
Route::get('/category/{id}', [
'uses' => 'PagesController@categoryDisplay',
'as' => 'category.show'
]);
}
这是我的ProductController.php,用于显示子类别下的所有产品:
class PagesController extends Controller {
public function categoryDisplay($id) {
$products = Product::all();
//$cat_id = Product::where('cat_id', '=', 3);
return view('category.show', compact('products'));
}
}
这是我试图展示产品的页面:
@extends('app')
@section('content')
<div class="container">
<h3 class="text-center">
Hi
@foreach($products as $product)
{{ $product->product_name }} <br>
@endforeach
</h3>
</div>
@endsection
我的分类模型:
class Category extends Model {
protected $table = 'categories';
protected $fillable = ['category'];
/**
* One sub category, belongs to a Main Category ( Or Parent Category ).
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function parent() {
return $this->belongsTo('App\Category', 'parent_id');
}
/**
* A Parent Category has many sub categories
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function children() {
return $this->hasMany('App\Category', 'parent_id');
}
/**
* One Category can have many Products.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function product() {
return $this->hasMany('App\Product', 'id');
}
}
我的产品型号:
class Product extends Model {
protected $table = 'products';
protected $fillable = [
'product_name',
'price',
'cat_id'
];
/**
* One Product can have one Category.
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function category() {
return $this->hasOne('App\Category', 'id');
}
}
这就是我的产品表的样子:
&#34; CAT_ID&#34;是产品子类别
正如你在控制器中看到的那样,如果我传入一个实际数字,如3,它将显示该cat_id下的所有产品,但显然我需要它是动态的。
答案 0 :(得分:0)
我明白了:我不得不改变一些像我的路线:
<?php
echo implode(', ', array_column($qty, 'qty'));
?>
我的控制器:
Route::get('category/{id}','PagesController@displayProducts');