Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Crazylife's avatar

Where should i validate my request when there's controllers and services?

I have my request validation on services, and then my controller looks in this way.

    /**
     * Delete a company.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request, int $companyId)
    {
        try {
            app(DestroyCompany::class)->execute([
                'account_id' => auth()->user()->id,
                'company_id' => $companyId,
            ]);
        } catch (Exception $e) {
            return $this->respondInvalid();
        }

        return $this->respondObjectDeleted($companyId);
    }

May i know which is good practice for validate request? Should i validate request in controller or service layer?

0 likes
8 replies
Crazylife's avatar

Yeah, i am using form request too. I am placing it in my service layer. Just wondering should it be placed in controller or service? Or just self preferences.

SilenceBringer's avatar

controller is good place for form request, I think. No reason to call service at all if validation will fail (in case of validaton in service you still doing service call first, and then validation failes)

1 like
martinbean's avatar

@crazylife You should be validating the data in whatever layer the input’s coming from. So in your case, the controller (ideally in a form request so your controller method is only invoked if the data is valid).

You should only be passing validated data to any service classes or models.

Your controllers shouldn’t be full of try/catch blocks either. Any domain exceptions you can catch in your exception handler and return an appropriate response. In your example, you’re just “black-holing” any exception thrown by catching it and returning a generic error response, so if an exception is thrown, you’re not going to know about it because it’ll never be logged. So a user’s going to say, “I got an error trying to delete a company” and you’re going to have no record of that error.

1 like
bloup's avatar

@martinbean "You should only be passing validated data to any service classes or models." Not always true...

Snapey's avatar

@bloup whats your point? Your opinion is clearly wrong so I don't know why you posted this 2 years later?

martinbean's avatar

@bloup Bit weird to find a two-year-old post and contest it as your second post on the forum. Have I upset you in the past or something…?

Crazylife's avatar

Thanks guys for the valued feedback!

2 likes

Please or to participate in this conversation.