Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

api-platform filter out the soft deleted items

I have setup the soft delete for my Store entity by using softdelete.

This is my filter setup in the doctrine.yml:

doctrine:
    # ...
    orm:
        # ...
        filters:
            softdeleteable:
                class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
                enabled: true

So when I hit e.g. the URL /stores only the active stores are returned, but if I change the config to enabled: false it will give me all the results including deleted items, which is correct.

Now what I want to achieve is pass a query parameter from front-end like /stores?deleted=1 and then I want to get all the data, if no deleted=1 found only the active items

like image 852
Kalhan.Toress Avatar asked Oct 18 '25 03:10

Kalhan.Toress


1 Answers

Why not create an event listener that uses the Request object and Doctrine's entity manager, and disables this filter? Something like this:

class FilterListener implements EventSubscriberInterface
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            RequestEvent::class => 'onKernelRequest',
        ];
    }

    public function onKernelRequest(RequestEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }

        $request = $event->getRequest();
        if ($request->query->getBoolean('deleted')) {
            $this->entityManager->getFilters()->disable('softdeleteable');
        }
    }
}
like image 113
Nico Haase Avatar answered Oct 20 '25 18:10

Nico Haase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!