Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

Filters: Searching Results

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

Some of our dragon treasures are currently published and some are unpublished. That's thanks to DragonTreasureFactory, where we randomly publish some but not others.

Right now, the API is returning every last dragon treasure. In the future, we're going to make it so that our API automatically returns only published treasures. But to start, let's at least make it possible for our API clients to filter out unpublished results if they want to.

Hello ApiFilter

How? By Leveraging filters. API Platform comes with a bunch of built-in filters that allow you to filter the collections of results by text, booleans, dates and much more.

Here's how it works: above your class, add an attribute called ApiFilter.

There are typically two ingredients that you need to pass to this. The first is which filter class you want to use. And if you look at the documentation, there's a bunch of them, like one called BooleanFilter that we'll use now and another called SearchFilter that we'll use in a few minutes.

Pass this BooleanFilter - the one from ORM, since we're using the Doctrine ORM - because we want to allow the user to filter on a boolean field.

The second thing you need top pass is properties set to an array of which fields or properties you want to use this filter on. Set this to isPublished:

... lines 1 - 4
use ApiPlatform\Doctrine\Orm\Filter\BooleanFilter;
use ApiPlatform\Metadata\ApiFilter;
... lines 7 - 38
#[ApiFilter(BooleanFilter::class, properties: ['isPublished'])]
class DragonTreasure
{
... lines 42 - 164
}

Using the Filter in the Request

All right! Go back to the documentation and check out the GET collection endpoint. When we try this... there's a new isPublished field! First, just hit "Execute" without setting that. When we scroll all the way down, there we go! hydra:totalItems: 40. Now set isPublished to true and try it again.

Yes! We have hydra:totalItems: 16. It's alive! And check out how the filtering happens. It's dead simple via a query parameter: isPublished=true. Oh, and it gets cooler. Look at the response: we have hydra:view, which shows the pagination and now we also have a new hydra:search. Yea, API Platform actually documents this new way of searching right in the response. It's saying:

Hey, if you want, you can add a ?isPublished=true query parameter to filter these results.

Pretty stinking cool.

Adding Filters Directly Above Properties

Now, when you read about filters inside of the API Platform docs, they pretty much always show it above the class, like we have. But you can also put the filter above the property it relates to.

Watch: copy the ApiFilter line, remove it, and go down to $isPublished. Paste this above. And now, we don't need the properties option anymore... API Platform figures that out on its own:

... lines 1 - 38
class DragonTreasure
{
... lines 41 - 68
#[ApiFilter(BooleanFilter::class)]
private bool $isPublished = false;
... lines 71 - 164
}

The result? The same as before. I won't try it, but if you peek at the collection endpoint, it still has the isPublished filter field.

SearchFilter: Filter by Text

What else can we do? Another really handy filter is SearchFilter. Let's make it possible to search by text on the title property. This looks almost the same: above $title, add ApiFilter. In this case we want SearchFilter: again, get the one for the ORM. This filter also accepts an option. You can see here that, in addition to properties, ApiFilter has an argument called strategy. That doesn't apply to all filters, but it does apply to this one. Set strategy to partial:

... lines 1 - 5
use ApiPlatform\Doctrine\Orm\Filter\SearchFilter;
... lines 7 - 39
class DragonTreasure
{
... lines 42 - 48
#[ApiFilter(SearchFilter::class, strategy: 'partial')]
private ?string $name = null;
... lines 51 - 166
}

This will allow us to search on the title property for a partial match. It's a "fuzzy" search. Other strategies include exact, start and more.

Let's give it a shot! Refresh the docs page. And... now the collection endpoint has another filter box. Search for rare and hit Execute. Let's see, down here... yes! Apparently 15 of the results have rare somewhere in the title.

And again, this works by adding a simple ?name=rare to the URL.

Oh, let's also make the description field searchable:

... lines 1 - 5
use ApiPlatform\Doctrine\Orm\Filter\SearchFilter;
... lines 7 - 39
class DragonTreasure
{
... lines 42 - 48
#[ApiFilter(SearchFilter::class, strategy: 'partial')]
private ?string $name = null;
... lines 51 - 53
#[ApiFilter(SearchFilter::class, strategy: 'partial')]
private ?string $description = null;
... lines 56 - 167
}

And now... that shows up in the API too!

The SearchFilter is easy to set up... but it's a fairly simple fuzzy search. If you want something more complex - like ElasticSearch - API Platform does support that. You can even create your own custom filters, which we'll do in a future tutorial.

Alrighty: next, let's see two more filters: one simple and one weird... A filter that, instead of hiding results, allows the API user to hide certain fields in the response.

Leave a comment!

7
Login or Register to join the conversation
Pierre-A Avatar
Pierre-A Avatar Pierre-A | posted 4 months ago | edited

In the "Script" version of this tutorial, you forgot the call to ApiFilter class here:

use use ApiPlatform\Metadata\ApiFilter; // the line you forgot in the text version of the tutorial
use ApiPlatform\Doctrine\Orm\Filter\BooleanFilter;
#[ApiFilter(BooleanFilter::class, properties: ['isPublished'])]
class DragonTreasure
1 Reply
Jakub Avatar

Hi,
when you want to activate filters for all booleans by default in your resource you need to only put:
#[ApiFilter(BooleanFiler::class)]
above class and of course, remember about proper 'use' statements.

Jakub

1 Reply

Ha! I didn't know that - very cool!

Reply
Wael-G Avatar

I see that there are 2 classes BooleanFilter, one for mangoDB(ODM) and one for MySQL5(ORM), how would i make my application support both of them?

Reply

Hey @Wael-G

I'm not sure about the answer but your application will run on two different databases?

Reply
Wael-G Avatar

I am just assuming that I have 2 clients with different Database preferences.

Reply

In that case, I think you would have to implement some sort of a "select database" system and remember that option somehow (perhaps in cache). Then, any service communicating to the DB will have to check that config and use the corresponding DB. I'm not sure if there are bundles that can help you with it
Oh, also, you'll have to set up Doctrine to work with multiple databases https://symfony.com/doc/current/doctrine/multiple_entity_managers.html

I hope it helps. Cheers!

1 Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": ">=8.1",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "api-platform/core": "^3.0", // v3.0.8
        "doctrine/annotations": "^1.0", // 1.14.2
        "doctrine/doctrine-bundle": "^2.8", // 2.8.0
        "doctrine/doctrine-migrations-bundle": "^3.2", // 3.2.2
        "doctrine/orm": "^2.14", // 2.14.0
        "nelmio/cors-bundle": "^2.2", // 2.2.0
        "nesbot/carbon": "^2.64", // 2.64.1
        "phpdocumentor/reflection-docblock": "^5.3", // 5.3.0
        "phpstan/phpdoc-parser": "^1.15", // 1.15.3
        "symfony/asset": "6.2.*", // v6.2.0
        "symfony/console": "6.2.*", // v6.2.3
        "symfony/dotenv": "6.2.*", // v6.2.0
        "symfony/expression-language": "6.2.*", // v6.2.2
        "symfony/flex": "^2", // v2.2.4
        "symfony/framework-bundle": "6.2.*", // v6.2.3
        "symfony/property-access": "6.2.*", // v6.2.3
        "symfony/property-info": "6.2.*", // v6.2.3
        "symfony/runtime": "6.2.*", // v6.2.0
        "symfony/security-bundle": "6.2.*", // v6.2.3
        "symfony/serializer": "6.2.*", // v6.2.3
        "symfony/twig-bundle": "6.2.*", // v6.2.3
        "symfony/ux-react": "^2.6", // v2.6.1
        "symfony/validator": "6.2.*", // v6.2.3
        "symfony/webpack-encore-bundle": "^1.16", // v1.16.0
        "symfony/yaml": "6.2.*" // v6.2.2
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.4", // 3.4.2
        "symfony/debug-bundle": "6.2.*", // v6.2.1
        "symfony/maker-bundle": "^1.48", // v1.48.0
        "symfony/monolog-bundle": "^3.0", // v3.8.0
        "symfony/stopwatch": "6.2.*", // v6.2.0
        "symfony/web-profiler-bundle": "6.2.*", // v6.2.4
        "zenstruck/foundry": "^1.26" // v1.26.0
    }
}
userVoice