I've created an API server using Laravel and set up FormRequests to handle incoming requests to the server. It all worked well. Now I'm trying to switch my API server to follow https://jsonapi.org/ specification, and I have no clue how to switch validation to handle complex incoming (POST, PUT, PATCH) JSON structure.
The only solution that I found working is to use in each FormRequest extended class, rules, following the pattern shown in the code block.
/**
* Get the validation rules that apply to the request.
*/
public function rules(): array
{
return [
'data' => 'required',
'data.type' => 'required|string',
'data.id' => 'sometimes|required|string',
'data.attributes' => 'sometimes|required',
'data.attributes.name' => 'string',
// ...
];
}
/**
* Get data to be validated from the request.
*/
protected function validationData(): array
{
return $this->json()->all();
}
The solution I came up with does the job, but I'm looking for a more DRY solution since this solution gets very messy if I'm validating more complex and nested JSON structure.