I'm interested to find out how you guys would approach creating filterable results for an API (In Laravel). The filterable options would be sent via a URL parameter.
I'm struggling to get my head around the most efficient way to code this, I mean.. I initially began using If Else and checking if the request has an input.... Which means every combination of filter options would require a conditional....
Any guidance would be massively appreciated. Well and truly lost here! :P
You might want to take a look at query scopes, you still need a way to check if the filter variable is set or not. You can however check in your query scope if the given value is set or not and based on that add it to the query or not.
public function scopePerformSearch(Request $request, $query)
{
$query->where('field', $request->field);
return $query;
}
Inside of the model would be an okay place to start? This will then be performing the said query on the model, right?
I could then access that function in my controller like:
ModelName::PerformSearch()->get();
right?
I can begin building more complex alternatives once I know where I stand, your information on checking if the value is set or not is great. That will cut out the need to check before running the query and instead run the query where the values matter, right?
You concatenat the fields in the request to a query. As @bobbybouwmann showed, you start tour base query and in each if statement concatenat your where portion of the query. At the end your search function should have the query built up and concatenat the get() to exacute the query.