1

I want to make a filter with query params, here I want to make 3 where, but if one of them is not there, then it will not be a problem because it will display according to the filter only, and if there is no query string then it will display all data

public function VendorInfoFilter(Request $request)
    {
        $vendor  = DB::table('schema.data as d')
                    ->where('d.status','=',$request->status)
                    ->orderBy('d.id')
                    ->get();   
        return response()->json($vendor);

    }
3
  • 2
    laraveldaily.com/less-know-way-conditional-queries Commented Dec 23, 2019 at 10:22
  • thankyou sir, it'works but now i have error for filter second SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input value for enum Commented Dec 23, 2019 at 10:42
  • Post your code in question. Commented Dec 23, 2019 at 10:42

2 Answers 2

2
public function VendorInfoFilter(Request $request)
    {
        $vendor  = DB::table('schema.data as d')
                    ->when($request->status, function ($q, $status) { 
                       return $q->where('d.status','=', $status);
                    })
                    ->when($request->status_two, function ($q, $status_two) { 
                       return $q->where('d.status_two','=', $status_two);
                    })
                    ->orderBy('d.id')
                    ->get();   
        return response()->json($vendor);

    }
Sign up to request clarification or add additional context in comments.

2 Comments

thank you sir, but now i found error like this SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input value for enum
Your query contains enum that doesn't accept/declare on the table enum field. Show me your table structure.
1

Take as reference, exact code might not work for you.

public function VendorInfoFilter(Request $request)
{
    $vendor  = DB::table('schema.data as d');

    if (!empty($request->status_one)) {
        $vendor = $vendor->where('d.status','=', $request->status_one);    
    }

    if (!empty($request->status_two)) {
        $vendor = $vendor->where('d.status','=', $request->status_two);  
    }

    if (!empty($request->status_three)) {
        $vendor = $vendor->where('d.status','=', $request->status_three); 
    }

    if (empty($request->status_one) && empty($request->status_two) && empty($request->status_three)) {
        $vendor= $vendor->where('d.status','=', $request->status_one)->where('d.status','=', $request->status_two)->where('d.status','=', $request->status_three);
    }

    $result = $vendor->orderBy('d.id')
                ->get();   

    return response()->json($result);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.