I have created a request class for an update API request. In the rules method I have the fields to validate. For one field I have to do a more complex validation.
Example
ModelA should be updated. But only if the owner (User) of the ModelA is null
in a field x (special_field_x
).
ModelA belongsTo User
User hasMany ModelA
ModelA [id (int), title (string), owner (int)]
User [id (int), name (string), special_field_x (string, nullable)]
My approach & question
I found an interesting rule function in the Laravel documentaion which I tried. It works but I wonder if this is the right function and if there is another way?
// ModelARequest.php
public function rules(PermissionRepository $permissionRepository)
{
return [
'title' => 'required',
'owner' => ['required', 'exists:users,id',
Rule::prohibitedIf($modelA->responsible->isUserEnable())], // isUserEnable returns a boolean
// ModelA responsible Method
public function responsible(): BelongsTo
{
return $this->belongsTo(User::class);
}
2
Answers
You can do:
This means that
special_field_x
must beNULL
. You can add more condition using (,) column name and value.the answer given before is a good one in my opinion, the one you also found is a good one, however I suggest another method if it can help you
To perform more complex validation on a specific field when updating an A model using a custom query class, you can follow these steps:
Create a custom query class using the Laravel artisan command:
Open the generated UpdateModelARequest class and modify the rules method by adding the specific validation for the special_field_x
I don’t pretend to say that it will solve your problem but it is a proposal