Undefined variable – bootstrap pagination – Laravel

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]);
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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();

Method 2

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() !!}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x