forms - Laravel - can I inject a FormRequest inside a FormRequest? -
i have complex set of rules build dynamically ideally need 1 set of rules validated before move on next, i.e.
i have json object {data: {}}
, want check exists before move on validate fields nested in data
, have other nested fields etc etc.
i thought having 1 formrequest
class, apirequest
, validate data
, another, uploadrequest
, adds further rules on basis data
has been validated.
i can this, , works, injecting apirequest
inside constructor of uploadrequest
, allows full set of rules validated in apirequest
, before moving on next set:
/** * uploadrequest constructor. * @param apirequest $apirequest */ public function __construct(apirequest $apirequest) { // if got here, apirequest passed validation, woo! }
does seem anti pattern or 'wrong' way handle this? trying think of request being made of mini requests i.e. upload request via api api request, followed upload request etc. i'm not sure if i'm trying justify myself.
any appreciated.
thanks!
you can have 1 apirequest
class validates mandatory parameters endpoints.
class apirequests extends formrequest { public function rules() { return [ 'data' => 'required', 'data.field_1' => 'required|string', 'data.field_2' => 'required|string' ]; } }
and let's api has endpoint edits user's profile. , request made endpoint must include first_name
, last_name
. new class extends apirequest
can made:
class edituserrequest extends clientrequest { public function rules() { return array_merge(parent::rules(), [ 'params.first_name' => 'required', 'params.last_name' => 'required', ]); } }
that merge rules apirequest
required edituserrequest
.
and in controller (eg. userscontroller
):
public function update(edituserrequest $request) { .... code goes here... }
Comments
Post a Comment