Reputation: 103
I have a controller that filter data from the database an send it to the view where i am using bootstrap pagination to show it on multiple pages... the data get listed on the view and every Everything work fine, but the problem is when i try to go the second page i get this error: Undefined variable: filtredPosts
this is the controller.
public function filter(Request $request){
$query = Post::query();
if ($request->country){
$query->where('country','=',$request->country);
}
if($request->city){
$query->where('city','=',$request->city);
}
if($request->type){
$query->where('type','=',$request->type);
}
if($request->sortby){
if ($request->sortby=='newest'){
$filtredPosts = $query->orderBy('created_at', 'desc')->paginate(9);
$sortby = 'newest';
}elseif ($request->sortby=='oldest'){
$filtredPosts = $query->orderBy('created_at', 'asc')->paginate(9);
$sortby = 'oldest';
}
}
return view('posts.postDashboard',['posts'=>$filtredPosts, 'sortby'=>$sortby, 'country'=>$request->country,'city'=>$request->city,'type'=>$request->type]);
}
Upvotes: 0
Views: 2336
Reputation: 2602
Your variable filtredPosts
is defined only if the $request->sortby
is present.
If your request doesn't have a sortby
key, this variable will be undefined.
You can solve it defining the variable before the if($request->sortby)
check:
...
$filtredPosts = $query;
if($request->sortby){
if ($request->sortby=='newest'){
$filtredPosts = $query->orderBy('created_at', 'desc')->paginate(9);
$sortby = 'newest';
}elseif ($request->sortby=='oldest'){
$filtredPosts = $query->orderBy('created_at', 'asc')->paginate(9);
$sortby = 'oldest';
}
}
Also, in your blade view, you need to pass the query string to the pagination using
$posts->withQueryString()->links();
Upvotes: 2
Reputation: 34708
You did not provide your pagination code on your blade, may be its something like :
{{ $posts->links() }}
You need to pass extra parameter with appends
on Paginator method, like :
{!! $posts->appends(['sortby' => $sortby, 'country' => $country, 'city' => $city])->links() !!}
On Laravel 7 or above version, you can call the withQueryString()
method on your Paginator instance :
{!! $posts->withQueryString()->links() !!}
Upvotes: 1