i want to filter annonces according to their category, but it gives me error Call to undefined method App Listing :: categories ().
AnnoncesController.php
public function index() { if (request()->category) { $annonces = Annonce::with('categories')->whereHas('categories', function ($query){ $query->where('slug',request()->category); }); $categories = Category::all(); }else{ $categories = Category::all(); $annonces = Annonce::paginate(4); } return view('annonces.index')->with([ 'categories' => $categories, 'annonces' => $annonces ]); }
index.blade.php
<div class="row"> <div class="col-md-12 gallery-filter"> <div class="button-panel"> <button data-filter="all" class="btn btn-primary ">All</button> @foreach($categories as $category) <a href="{{ route('annonces.index',['category'=>$category->slug]) }}" data-filter=".{{ $category->slug }}" class="btn btn-primary ">{{ $category->name }}</a> @endforeach </div> </div> </div>
Annonce.php
public function category() { return $this->belongsTo('AppCategory'); }
Category.php
protected $table = 'category'; public function annonces(){ return $this->hasMany('AppAnnonce'); }
Advertisement
Answer
as per your code you need to change this categories
to category
because in Annonce.php
you created category
relationship
public function index() { if (request()->category) { $annonces = Annonce::with('category')->whereHas('category', function ($query) { $query->where('slug', request()->category); }); $categories = Category::all(); } else { $categories = Category::all(); $annonces = Annonce::paginate(4); } return view('annonces.index')->with([ 'categories' => $categories, 'annonces' => $annonces ]); }