Reputation: 155
I have a complex set of rules that I build dynamically but ideally I need one set of rules to be validated before I move on to the next, i.e.
I have a json object {data: {}}
, which I want to check exists before I move on to validate fields nested in data
, which have other nested fields etc etc.
I thought about having one FormRequest
class, say ApiRequest
, which could validate data
, then another, say UploadRequest
, which adds further rules on the basis that the data
has already been validated.
I can do this, and it works, by injecting ApiRequest
inside the constructor of UploadRequest
, which allows the full set of rules to be validated in ApiRequest
, before moving on to the next set:
/**
* UploadRequest constructor.
* @param ApiRequest $apiRequest
*/
public function __construct(ApiRequest $apiRequest) {
// If we got here, ApiRequest passed validation, woo!
}
Does this seem like an anti pattern or the 'wrong' way to handle this? I was trying to think of a request being made up of mini requests i.e. an upload request via the api is really an api request, followed by an upload request etc. But I'm not sure if I'm just trying to justify this to myself.
Any help would be greatly appreciated.
Thanks!
Upvotes: 1
Views: 1050
Reputation: 10219
You can have one ApiRequest
class that validates all mandatory parameters for all endpoints.
class ApiRequests extends FormRequest
{
public function rules()
{
return [
'data' => 'required',
'data.field_1' => 'required|string',
'data.field_2' => 'required|string'
];
}
}
And let's say your API has an endpoint that edits user's profile. And the request made to that endpoint must include first_name
and last_name
. So a new class that extends ApiRequest
can be made:
class EditUserRequest extends ClientRequest
{
public function rules()
{
return array_merge(parent::rules(), [
'params.first_name' => 'required',
'params.last_name' => 'required',
]);
}
}
That will merge all rules from ApiRequest
with those required for EditUserRequest
.
And then in your controller (eg. UsersController
):
public function update(EditUserRequest $request) {
.... your code goes here...
}
Upvotes: 1