I'm not being able to append the result with query. I'm filtering the result with category on the page and trying to add pagination. When a user clicks on category only category related products should be displayed and on pagination I want to keep the selected category. I'm getting this error:
Facade\Ignition\Exceptions\ViewException Call to undefined method Illuminate\Database\Eloquent\Builder::appends() (View: D:\Xampp\htdocs\ProjectName\resources\views\products\index.blade.php)
I have tried this from laravel docs
{{ $users->appends(['category' => 'query'])->links() }}
Here's my Controller:
public function index(Request $request)
{
// If the category is selected
if(request()->category) {
$products = Product::with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->category);
});
$categories = Category::all();
$categoryName = optional($categories->where('slug', request()->category)->first())->name;
}else {
$products = Product::paginate(9);
$categories = Category::all();
$categoryName = 'All Products';
}
return view('products.index')->with([
'products' => $products,
'categories' => $categories,
'categoryName' => $categoryName,
]);
}
This is my blade file:
<h4>{{ $categoryName }}</h4>
@forelse ($products as $product)
<div class="card mb-3 shadow" style="">
<div class="row no-gutters">
<div class="col-md-4 d-flex justify-content-around p-2 border">
<img src="/storage/products/{{ $product->image }}" class="card-img">
</div>
<div class="col-md-8 p-2">
<div class="card-body">
<h5 class="card-title">{{ $product->title}}</h5>
<p class="card-text"> {!! \Illuminate\Support\Str::limit($product->text, $limit = 100) !!} </p>
<div class=""><a href="/products/{{ $product->slug }}"><button class="btn btn-outline-warning float-left">View Cataloge</button></a>
</div>
</div>
</div>
</div>
</div>
@empty
<div class="card">
<div class="card-title p-5 shadow bg-light">
<h5>No products found</h5>
</div>
</div>
@endforelse
<div class=" d-flex justify-content-around">
{{ $products->appends(request()->input())->links() }}
</div>
{{ $products->appends(request()->except('page'))->links() }}
try this way – Akhtar Munir