Laravel - Validation With Custom Value

- 1 answer

My form has a textbox, and 3 radio buttons. The radio buttons indicate what type of tool a user wants to use, but he needs to have them in his inventory. There are 3 types of tools, and each radio button can only be selected if he owns at least one of them.. I want to validate it to se if he actually owns one. In the sample below, the variables $tool1 - 3contain the count of how many of each tool the user has. (for example: $tool1 = 1, $tool2 = 3, $tool3 = 0) In this case, the validation should be Ok, if the user selected one of the first two radio buttons since he owns the tools needed, but should fail if he selects the third radio button.

The field 'tool' contains the actual selected tool, so tool can be tool1, tool2 or tool3.


$data = request()->validate([
        'name'=> 'required',
        'tool' => 'required',

how can this be done?



The following data structure you can do some nice tricks with and should be obtainable as i understand your domain.

$tools = collect(['tool1' => $tool1, 'tool2' => $tool2, 'tool3' => $tool3]);

Find all tools where count is higher than 0, filter() removes all null values and since 0 == null. To validate the input, we only need the name, we get that with keys().

// Should return 'tool1' and 'tool2' in an array from your example
$toolsOwned = $toolsOwned->filter()->keys();

Now we can use the In() validation to check if input is correct.

use Illuminate\Validation\Rules\In;


'tool' => ['required', new In($toolsOwned->all())],