phplaravelvalidationexistsrules

Laravel: custom array validation depends on previous selected value


Laravel version: 7.x

I have tested the code with hard-coded valid device_company_id (which is associated with the selected device) and it works fine.

Tables

device_companies
|- id
|- company_id
|- title
|- ...

devices
|- id
|- device_company_id
|- ...

Request data

Array
(
    ...

    [devices] => Array
        (
            [0] => Array
                (
                    [device_company_id] => 1
                    [device_id] => 2
                    [device_inventory_id] => null
                    [amount] => 
                    [refundable] => 
                    [description] => 
                )

        )
)

Rules:

...

$rules = array_merge($rules, [
    'devices' => [
        'required', 
        'array'
    ],
    'devices.*.device_company_id' => [
        'required', 
        'integer', 
        'exists:device_companies,id,company_id,' . auth()->user()->id
    ],
    'devices.*.device_id' => [
        'required', 
        'integer', 
        'exists:devices,id,device_company_id,devices.*.device_company_id'
    ],
]);

...

I need a custom validation rule for the exists validator to validate if device actually belongs the selected device_company or not. Because I don't want anyone opening the inspect tool, change the value and causing the application an error or anything like that.


Solution

  • Here is the link where I found the reference https://ericlbarnes.com/2015/04/04/laravel-array-validation/

    My code:

    ...
    
    $rules = [
        ...other rules
    ];
    
    $newRules = [
        'devices' => [
            'required', 
            'array'
        ],
        'devices.*.device_company_id' => [
            'required', 
            'integer', 
            'exists:device_companies,id,company_id,' . auth()->user()->id
        ],
    ];
    
    foreach($data['devices'] as $key => $array)
    {
        $newRules["devices.{$key}.device_id"] = [
            'required',
            'integer',
            "exists:devices,id,device_company_id,{$array["device_company_id"]}",
        ];
    }
    
    $rules = array_merge($rules, $newRules);
    
    ...
    

    Although, this code is working for me but I feel its not the proper way to do it. It feels kind of a way around instead of the proper solution. If anyone finds a better solution then please do post your answer.


    Hope this can be helpful for someone. Thanks :)