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

Sys Auditing's avatar

use laravel FormRequest prepareForValidation method for multiple array of objects

how to use laravel FormRequest prepareForValidation method for multiple array of objects?

curl -i -X POST \
-H'Content-Type: application/json' \
-H'Accept: application/json'\
-H'Authorization: Bearer PLKKSDSDSD....'\
//array of objects
-d'[{
    "account_id": "ABC",
},
{
    "account_id": "DEF",
}]' \
https://domain/api/account
protected function prepareForValidation()
{

    $account_id = $this->account_id;
    $account = Account::select('id')->where('name', $account_id)->first();

    $this->merge([
        'account_id'  => is_null($account) ? 0 : $account->id,
    ]);

}

when using post data as a simple object i can use prepareForValidation works as a charm, but when using array of objects like demonstrated above i don't undestdand how to do.

Any help will be appreciated.

0 likes
4 replies
martinbean's avatar

@sys auditing Dude, you don’t need the prepareForValidation method! I’ve been telling you this for two days now on the Laravel Discord.

You have request data coming in. Just validate it. You don’t need to manipulate it or merge it. Again, stop trying to shoe-horn in usages of framework features that you don’t need. If you want to validate the incoming account IDs, then do so:

public function rules()
{
    return [
        '*.account_id' => 'exists:accounts,id',
    ];
}
Sys Auditing's avatar

I don't have the issue on validation side i did the same as your unswer, but as you can see my frontend post a data (account_id) via an API, this account_id posted as name (client knows only names) and i would like to save data as ID that why i'm using this statement : $account = Account::select('id')->where('name', $account_id)->first();

In order to do that i'm preparing data before validation.

That's my history dude @martinbean

martinbean's avatar

account_id posted as name (client knows only names) and i would like to save data as ID

@sys auditing Then that’s nothing to do with validation. Validate that the names the front-end is posting are existing accounts:

public function rules()
{
    return [
        '*.account_id' => ['required', 'string', 'exists:accounts,name'],
    ];
}

Then convert those names to IDs in your controller:

public function someAction(SomeFormRequest $request)
{
    $names = Arr::pluck($accounts, 'account_id');

    $accounts = Account::whereIn('name', $names)->get();

    // Now do something with your retrieved account models here...
}

You don’t need prepareForValidation at all.

Please or to participate in this conversation.