1

I just start to use Api platform and immediately stuck with problem how to filter data. I have entity User and i want to filter data that are present in response ( JSON API format)

{
    "links": {
        "self": "/api/users"
    },
    "meta": {
        "totalItems": 2,
        "itemsPerPage": 30,
        "currentPage": 1
    },
    "data": [
        {
            "id": "/api/users/1",
            "type": "User",
            "attributes": {
                "_id": 1,
                "username": "jonhdoe",
                "isActive": true,
                "address": null
            }
        },
        {
            "id": "/api/users/3",
            "type": "User",
            "attributes": {
                "_id": 3,
                "username": "test",
                "isActive": true,
                "address": null
            }
        }
    ]
}

so I want to remove e.g. User with id 3, but not use filters sent via request. I just want to set filter that will be always run when someone go to /api/users. I look to api-platform extensions but this will be applied on each request e.g. /api/trucks. So at end I just want to get something like

{
    "links": {
        "self": "/api/users"
    },
    "meta": {
        "totalItems": 1,
        "itemsPerPage": 30,
        "currentPage": 1
    },
    "data": [
        {
            "id": "/api/users/1",
            "type": "User",
            "attributes": {
                "_id": 1,
                "username": "jonhdoe",
                "isActive": true,
                "address": null
            }
        }
    ]
}
1

1 Answer 1

3

As you pointed out, extensions are the way to go.

The applyToCollection method gets a $resourceClass parameter containing the current resource class.

So you can apply the WHERE clause only for a specific class in this method like:

public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
{
    if (User::class === $resourceClass) {
        $queryBuilder->doSomething();
    }
    // Do nothing for other classes
}
Sign up to request clarification or add additional context in comments.

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.