Skip to content
Advertisement

Laravel multiple filter with search

I want to search service providers and products, and filter by location and by service, or by location and by-products. i am using below code` $results = new ClientProfile;

    if (request()->has('service-provider')) {
        $results = $results->where('jobsc_id', request('service-provider'));
    } elseif(request()->has('product')) {
        $results = $results->where('product_id', request('product'));
    } elseif(request()->has('city')){
        $results = $results->where('divsec_id', request('city'));
    } else {
        $results = ClientProfile::searched();
    }  
    
    $results = $results->where('profile_state', 'active')->paginate(10)->appends([
        'service-provider' => request('service-provider'),
        'product' => request('product'),
        'city' => request('city'),
    ]);
    
            
    return view('results')->with('results', $results);`

although it shows URL as domain.com/results?product=2&city=78 it shows all products without filter by city

Advertisement

Answer

You use if elseif therefore it when finding one, in the second also does not come.

use when instead if else

$results = new ClientProfile::when(request()->has('service-provider'), function($q){
    $q->where('jobsc_id', request('service-provider'));
})
->when(request()->has('product'), function($q){
    $q->where('product_id', request('product'));
})
->when(request()->has('city'), function($q){
    $q->where('divsec_id', request('city'));
})
->when(count($request->all()) === 0, function($q){
    $q->searched();
})
->where('profile_state', 'active')->paginate(10)->appends([
    'service-provider' => request('service-provider'),
    'product' => request('product'),
    'city' => request('city'),
]);

        
return view('results')->with('results', $results);`
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement