Search code examples
laravelpaginationlaravel-pagination

Second page of paginate won't display the filtered data


I'm want to use paginate in laravel but didn't work perfectly. When i paginate the filtered data it worked fine, but only for the first page.The problem is when i moved to the second page, it will display the second page of all data not the filtered data. i want it so the second page will display the second page of filtered data

in blade.php I'm using links to call the paginate(for moving page)

<div class="paginate">
     {{ $data->links() }}
</div>

Here's the filter controller

function filter(Request $request){
        $data = profiles::when($request->has('pNamaLengkap'), function($query) use ($request){
            $query->where('pNamaLengkap','like','%'.$request->pNamaLengkap.'%');
        });
        if($request->pJobDescription != 'All'){
            $data = $data->where('pJobDescription','like','%'.$request->pJobDescription.'%');
        }
        if($request->pUnitKerja != 'All'){
            $data = $data->where('pUnitKerja','like','%'.$request->pUnitKerja.'%');
        }
        if($request->pDirectorate != 'All'){
            $data = $data->where('pDirectorate','like','%'.$request->pDirectorate.'%');
        }
        if($request->pRank != 'All'){
            $data = $data->where('pRank','like','%'.$request->pRank.'%');
        }

        return view('export', [
            'data' => $data->paginate(5),
            'jobdescription' => jobdes::all(),
            'unitkerja' => unitkerja::all(),
            'direktorat' => direktorat::all(),
            'rank' => rank::all(),
            'oldjob' => $request->pJobDescription,
            'oldunit' => $request->pUnitKerja,
            'olddir' => $request->pDirectorate,
            'oldrank' => $request->pRank,
            'oldname' => $request->pNamaLengkap
        ]);

        // return redirect('export')->with([
        //     'data' => $data,
        //     'jobdescription' => jobdes::all(),
        //     'unitkerja' => unitkerja::all(),
        //     'direktorat' => direktorat::all()
        // ]);
    }

I'll make an example from a picture

Filtered JobDescription Page 1

Page 2 that reset the filter and display all data

in the URL parameter it change it from

http://127.0.0.1:8000/filterexport?pNamaLengkap=&pJobDescription=Full+Stack+Developer&pUnitKerja=All&pDirectorate=All&pRank=All&export=Filter

into

http://127.0.0.1:8000/filterexport?page=2

for extra note, the paginate is working but just didn't work when you want to view the second page because somehow it reset the input filter

Thank you for reading this page, i really need help in this one


Solution

  • $data->paginate(15)->withQueryString();
    

    use withQueryStrings() method with paginated data.