Reputation:
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
Route::get('/admin/category/single/{categoryId}', ['uses' => 'AdminController@categoriesCheck']);
Then in AdminController I have added
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?
currently I have dummy 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
Upvotes: 0
Views: 5232
Reputation: 9749
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:
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
Upvotes: 4