joshstaff's avatar

Filtering API results effectively

Hey all,

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

0 likes
5 replies
bobbybouwmann's avatar

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.

joshstaff's avatar

Hi @bobbybouwmann thanks for your time and reply.

Placing something like:

     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?

Thanks again! :D

bobbybouwmann's avatar

You still need to check if the value exists in the request and apply that to your query for example

public function search(Request $request)
{
    $user = User::query();

    if ($request->has('active')) {
        $user = $user->isActive();
    }

    if ($request->has('name')) {
        $user = $user->name($request->get('name'));
    }
}

// User.php

public function scopeIsActive($query)
{
    return $query->where('active', 1);
}

public function scopeName($query, $name)
{
    return $query->where('LIKE', '%' . $name . '%');
}
joshstaff's avatar

Got you - So now I need to work out the way I am going to create a query without knowing which filter options the user will be using.

Do you think I can use foreach to get each parameter the user has sent and then chain query scopes to run my query? Or is my logic way off? :P

Thanks again for your help :)

jekinney's avatar

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.

Please or to participate in this conversation.