0
votes

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.

1
This sounds like you need a custom validation rule. See this reference: laravel.com/docs/7.x/validation#custom-validation-rules - Daniel Petrovaliev
Thanks @DanielPetrovaliev, but I must tell you that I went through the documentation and couldn't find the solution. However, I found the a way out of this problem. I am posting it shortly. Although, it works but I feel this can be improved. If anyone find a better way for this issue, please post your answer. Thank you :) - MrSingh

1 Answers

0
votes

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 :)