Search code examples
laravelvalidationlaravel-validation

Laravel validation depending on another model whose ID is on the same form


I have a form returning fields entity_id and price.

$validated = $request->validate([
            'entity_id' => ['required', 'integer'],
            'price' => ['required', 'numeric', 'min:1'],
        ]);

The price field should have a max rule, but that value comes from the chosen Entity that has a max_price field. That value should then be set as max. How can I do that?


Solution

  • You can do it with Custom validation.

    One of the custom validation is to use closure

    $validated = $request->validate([
                'entity_id' => ['required', 'integer'],
                'price' => [
                    'required', 
                    'numeric', 
                    'min:1', 
                    function ($attribute, $value, $fail) use ($request) {
                        $max = Entity::where('id',$request->entity_id)->value('max_price');
                        //$max will be the desired value OR NULL
                        if (isset($max) && $max < $value) {
                            $fail('The '.$attribute.' is higher than the allowed max '.$max.'.');
                        }
                    }
                ],
            ]);