[英]Showing products only from selected category in Laravel
I'm trying to show products only from selected category but something goes wrong and I still can't understand what. 我试图仅显示所选类别的产品,但是出了点问题,我仍然不明白是什么。
What I have done so far is I have added route in routes.php
到目前为止,我所做的是在
routes.php
添加了route
Route::get('/admin/category/single/{categoryId}', ['uses' => 'AdminController@categoriesCheck']);
Then in AdminController I have added 然后在AdminController中我添加了
public function categoriesCheck() {
$products = Product::paginate(15);
$categories = Categories::all();
return View::make('site.admin.single_category', [
'categories' => $categories,
'product' => $products
]);
}
so 2 questions how if I click on category_id=1 how to make query to load only products where category_id=1 ( I have made column in product table which hold category_id for each product ) and how to make the view page? 所以有2个问题,如果我单击category_id = 1,如何进行查询以仅加载category_id = 1(我在产品表中的列中保存了每种产品的category_id)的产品,以及如何制作视图页面?
currently I have dummy single_category.blade.php
目前我有虚拟的
single_category.blade.php
@extends('layouts.master')
@section('title', 'Categories')
@section('content')
<div class="col-xs-12">
<h3>Products List</h3>
<hr />
<div class="row">
@foreach($products as $i => $product)
<div class="col-md-4">
<div class="panel panel-default text-center">
<div class="panel-heading">{{{ $product['title'] }}}</div>
<div class="panel-body min-h-230">
@if($product['image'])
<img class="max-150" src="{{ $product['image'] }}" alt="{{{ $product['title'] }}}" />
<br /><br />
@endif
{{ str_limit($product->description_small, 100) }}
@if (strlen($product->description_small) > 100)
<br/><br /> <a href="{{ URL::to('product/single/' . $product->product_id) }} " class="btn btn-info btn-block view-more">View More</a>
@endif
</div>
</div>
</div>
@if(($i+1) % 3 == 0)
</div><div class="row">
@endif
@endforeach
</div>
<hr />
{{ $products->links() }}
</div>
@endsection
When I run the page now I got all products... no matter what category I click 当我现在运行页面时,我得到了所有产品……无论我单击哪个类别
First in your Category model you have to make the relationship with your Products so add this: 首先,必须在类别模型中与产品建立关系,因此添加以下内容:
public function products()
{
return $this->hasMany('Product');
}
Then in your controller you have to accept the category ID from the route and query a category by it: 然后,在您的控制器中,您必须接受路径中的类别ID并由此查询类别:
public function categoriesCheck( $categoryId )
{
$category = Categories::with('products')->findOrFail( $categoryId );
return View::make('site.admin.single_category', [
'category' => $category
]);
}
And finally in your view check if a category has products and if it has loop them: 最后,在您的视图中检查类别是否包含产品,以及是否有循环产品:
@if($category->products->count())
@foreach($category->products as $product)
//DIsplay product data
@endforeach
@endif
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.