Multiple optional scopes

Posted 6 months ago by audunru

Wondering how to apply multiple, optional scopes in my controller in the cleanest way.

The frontend can make a GET request like /api/v1/company/1/products or /api/v1/company/1/products?purchased_in=2018keyword=festivus, and my ProductController.php currently looks like this:

    public function index(FilterProducts $request, Company $company)
    {
        abort_unless(Auth::user()->can('view', $company), 403);
        $validated = $request->validated();

        if (isset($validated['purchased_in'])) {
            $products = $products->year($validated['purchased_in']);
        }
        if (isset($validated['keyword'])) {
            $products = $products->search($validated['keyword']);
        }

        return ProductResource::collection($products->get());
    }

I have other functions where the number of available scopes is even greater, so I'm thinking there must be a cleaner way to chain these together even though the frontend may not always specify purchased_in or keyword, and so on.

Please sign in or create an account to participate in this conversation.