skip to Main Content

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


  1. You can do:

    'exists:users,id,special_field_x,NULL'
    

    This means that special_field_x must be NULL. You can add more condition using (,) column name and value.

    Login or Signup to reply.
  2. 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:

    php artisan make:request UpdateModelARequest
    

    Open the generated UpdateModelARequest class and modify the rules method by adding the specific validation for the special_field_x

    $modelAId = $this->route('modelA'); // Obtenez l'ID du modèle A depuis la route
    
    return [
        'name' => 'required|string|max:255',
        'special_field_x' => [
            function ($attribute, $value, $fail) use ($modelAId) {
                $modelA = ModelA::find($modelAId);
                $owner = $modelA->owner;
    
                if (!is_null($owner) && $value !== $owner->special_field_x) {
                    $fail('Validation error message.'); // Remplacez par le message d'erreur souhaité
                }
            },
        ],
        // Autres règles de validation pour les autres champs de ModelA
    ];
    

    I don’t pretend to say that it will solve your problem but it is a proposal

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search