skip to Main Content

I have a problems on the pagination spesificly when try to searching data by some condition its work properly, But when i try to change the page the data wont sort by the condition.the the search work properly but it gone wrong when i change the page.

this is my code

    public function fotoTrxSearch(Request $request){

    $transaction = Foto::OrderByDesc('id');

    if($request->filled('name')){
        $transaction->where('name', 'like', "%{$request->name}%")->orderBy( 'id', 'desc');
    }
    if($request->filled('from') AND $request->filled('to')){
        $transaction->whereBetween('date', [$request->get('from'), $request->get('to')])->orderBy( 'id', 'desc');
    }
    if($request->filled('price')){
        $transaction->where('price','like', "%{$request->price}%")->orderBy( 'id', 'desc');
    }
    if($request->filled('folder')){
        $transaction->where('folder','like', "%{$request->folder}%")->orderBy( 'id', 'desc');
    }
    
    $transaction = new FotoCollection($transaction->paginate(150));

    return Inertia::render('Foto/FotoList',[ 'fotos' => $transaction]);
   
}

please give me some clue or hint, solution to fix this problems
Thankyou in advance

2

Answers


  1. You should persist the query result to a variable before pagination. This might work:

    public function fotoTrxSearch(Request $request){
    
        $transactions = Foto::OrderByDesc('id');
    
        if($request->filled('name')){
            $transactions = Foto::where('name', 'like', "%{$request->name}%")->orderBy( 'id', 'desc');
        }
        if($request->filled('from') AND $request->filled('to')){
            $transactions = Foto::whereBetween('date', [$request->get('from'), $request->get('to')])->orderBy( 'id', 'desc');
        }
        if($request->filled('price')){
            $transactions = Foto::where('price','like', "%{$request->price}%")->orderBy( 'id', 'desc');
        }
        if($request->filled('folder')){
            $transactions = Foto::where('folder','like', "%{$request->folder}%")->orderBy( 'id', 'desc');
        }
        
        $transactions = new FotoCollection($transactions->paginate(150));
    
        return Inertia::render('Foto/FotoList',[ 'fotos' => $transactions]);
       
    }
    
    Login or Signup to reply.
  2. If I understood you correctly, your conditions work properly only on the first page. On any other they don’t work. If that’s the case, I think this code should solve your problem, because it worked for me:

           $result = $transactions->paginate(150)
            ->appends(request()->query());
           ...
    

    Hope this helps! 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search