Reputation: 45
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"
}
]
}
]
}
Upvotes: 2
Views: 895
Reputation: 1045
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:
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.
Upvotes: 1