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.