skip to Main Content

I’m trying to make pagination after sorting in my Laravel project , so I did this method, it sorts my data but when I want to see next paginate table it shows me this error

SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'order clause'
SELECT * FROM `customers` ORDER BY `` DESC limit 3 OFFSET 3

My method

 public function Sortfilter(Request $request)
    {
        $active = Customer::where('active','=','1')->count();
        $inactive = Customer::where('active','=','0')->count();
        $customer = Customer::query();

        $customer = Customer::orderBy($request->filter,'desc')->paginate(3);
        return view('customers.index', compact('customer','inactive','active'));


    }

is there a method to save the $request->filter data when I click on next button

EDIT

when i sort my data the URL change like that : http://127.0.0.1:8000/sortCustomer?filter=phone&_token=9xw0q9MKa5ABZc4CwkLaPqf5ko4BhJ4ZaEk0VKYY

and when i click to the pagination button the URL be like that :

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

3

Answers


  1. The problem is sometimes your $request->filter is empty, so adding a default value when it’s empty fixes that.

    public function Sortfilter(Request $request)
    {
        $active = Customer::where('active','=','1')->count();
        $inactive = Customer::where('active','=','0')->count();
        $customer = Customer::query();
        $filter = $request->filter ?: 'created_at';
    
        $customer = Customer::orderBy($filter,'desc')->paginate(3)>appends(['filter' =>  $request->filter]);
        return view('customers.index', compact('customer','inactive','active'));
    }
    
    Login or Signup to reply.
  2. I think you are passing ” (null) in the first parameter of orderBy clause.

    please confirm that the value in the $request->filter parameter not null and it should be a column name as in the customer table.

    Login or Signup to reply.
  3. In Laravel there is the option to append query string values to pagination links.

    Using this your code could look like this:

    public function Sortfilter(Request $request)
    {
        $active = Customer::where('active','=','1')->count();
        $inactive = Customer::where('active','=','0')->count();
        $customer = Customer::query();
    
        $customer = Customer::orderBy($request->filter,'desc')->paginate(3)->withQueryString();
        return view('customers.index', compact('customer','inactive','active'));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search