Sys Auditing
Sys Auditing

Reputation: 76

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.

Upvotes: 1

Views: 610

Answers (1)

Alexander Ivashchenko
Alexander Ivashchenko

Reputation: 878

You need to iterate the array, apply your preparation for each object and then merge final array into request parameters.

protected function prepareForValidation()
{
    $parameters = $this->all();

    array_walk($parameters, function (&$object) {
        $object['account_id'] = Account::select('id')->where('name', $object['account_id'])->first();
    });

    $this->merge($parameters);
}

Upvotes: 0

Related Questions