2

Is there any solutions on how to change property names or attributes of JSON Request in Laravel?

Something like Eloquent API Resources but instead in responses, it will be done in requests before directing to the request validation?

From this,

{
    "agent_reference": "ABC-12345",
    "product_instance_id": "aca68c65-44c3-4ea1-a726-ca183de09a31",
    "add_ons": [
        "string"
    ],
    "transportation": "string",
    "guests": [
        {
        "guest_type_key": "string",
        "add_ons": [
            "string"
        ],
        "field_responses": [
            {
            "key": "string",
            "response": "string"
            }
        ]
        }
    ]
}

To this,

{
    "agent_id": "ABC-12345",
    "plan_id": "aca68c65-44c3-4ea1-a726-ca183de09a31",
    "additional_params": [
        "string"
    ],
    "pickup_place": "string",
    "visitors": [
        {
        "visitor_kty": "string",
        "additional_params": [
            "string"
        ],
        "responses": [
            {
            "id": "string",
            "result": "string"
            }
        ]
        }
    ]
}

1 Answer 1

1

Laravel 4 had support for such a thing, however, sadly, it got removed with the release of Laravel 5.

For Laravel 5.2+, the "neat" way of achieving this is is by overriding the validationData() method in your App\Http\Requests\FormRequest class.

Take a look at:

Illuminate\Foundation\Http\FormRequest

protected function validationData()
{
    return $this->all();
}

The function above is meant to return all inputs that will be sent to the validation, $this is the Request itself.

So, in your App\Http\Requests\FormRequest class, you define the very same method, get the inputs, sanitize as you want (even creating a whole new structure with different key names, as requested in your question), replace it in the request to persist and return, like so:

/**
 * Get data to be validated from the request.
 *
 * @return array
 */
protected function validationData()
{
    $inputs = $this->all();

    // Sanitize $inputs as your likes.

    $this->replace($inputs); // To persist.

    return $this->all();
}

This is how you get it done in Laravel 5.2+.

Hope it helps.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this sir but the thing is how can i change those property names especially nested arrays attributes in order to pass in this validationData function?
There's no out of the box way to achieve this with Laravel, you'll have to tackle it with pure php.
Thank you very much for this answer sir. God bless.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.