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

Synchro's avatar

Is it a good idea to fetch instances in form requests?

I'm using form requests in front of most of my controllers, and these tend to follow the pattern of validating and authorising the request only. It's very common for these requests to contain IDs of various entities, but I don't fetch those until I've received the request in the controller, so in my request I might have:

public function rules(): array
{
    return [
        'thing_id' => ['required', 'uuid', 'exists:things,uuid'],
   ];
}

and then in my controller:

$thing = Thing::whereUuid($request->thing_id);

I don't need to check whether it exists because that's already been validated.

I'm wondering if it's a good idea to fetch such instances in the form request (perhaps in an after() method) instead of the controller, so that in my controller I can simply refer to $request->thing. This would be the first time I'm using model instances in my request classes, and I'm not sure if it's a good idea or not.

Thoughts?

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

It is generally not recommended to fetch model instances in form requests. The main reason for this is that form requests should only be responsible for validating and authorizing the request data, and not for fetching data from the database. Fetching data from the database should be done in the controller or a service class.

However, if you still want to fetch model instances in form requests, you can do so in the withValidator method. Here's an example:

use Illuminate\Validation\Validator;

class MyFormRequest extends FormRequest
{
    public function rules()
    {
        return [
            'thing_id' => ['required', 'uuid', 'exists:things,uuid'],
        ];
    }

    public function withValidator(Validator $validator)
    {
        $validator->after(function () {
            $thing = Thing::whereUuid($this->thing_id)->firstOrFail();
            $this->merge(['thing' => $thing]);
        });
    }
}

In this example, we're using the withValidator method to add an after hook to the validator. In the hook, we're fetching the Thing model instance based on the thing_id input, and then merging it into the request data using the merge method. This will make the thing instance available in the controller via $request->thing.

Note that this approach can lead to performance issues if you're fetching a lot of data in the form request, so use it with caution.

Please or to participate in this conversation.