//my route
Route::get('catalogue/{categorie?}','App\Http\Controllers\CatalogueController@index')->name('catalogue');
//my function
function index($categorie = null )
{
if($categorie)
{
$products = \App\Models\Category::where('slug',$categorie)
->first()
->products()->paginate(12);
}else{
$products = \App\Models\Product::paginate(3);
}
$categories = \App\Models\Category::all();
$brands = \App\Models\Brand::all();
return view('catalogue.index',compact('products','categories','brands'));
}
//my view
<ul>
@foreach($categories as $categorie)
<li> <a href="{{route('catalogue',['slug'=>$categorie->slug])}}">{{$categorie->name}}</a> </li>
@endforeach
</ul>
I try to display my products by category.e.g.if I click on a category, all products belonging to that category should be displayed, but they don't.I observe the URL seems works (see screen) but no matter which category I click I always have only the same 3 products so I guess category does not exist. Why and how can i fix it please ? thank you
Based on the route definition above, your route accepts categorie
parameter, and not slug
.
Change your route in view to this:
<a href="{{route('catalogue',['categorie'=>$categorie->slug])}}">