0

I would like to validate an array by verifying that all the elements in an input is part of another array. For example, lets say I have three arrays:

$foo = ['John', 'Terry', 'Kim'];
$bar = ['John', 'Kim'];
$sub = ['John', 'Ringo'];

and I have a function called CompareArrays(). Doing CompareArrays($foo, $bar) would result in true because all the elements in $bar exists in $foo. However, CompareArrays($foo, $sub) would result in false because Ringo doesn't exist in foo. Implementing this in vanilla php is

!array_diff($foo, $bar)

How would I do this in a Laravel Validator without making a custom rule (v6.10) ?

1 Answer 1

0

You may use in_array:anotherfield.* rule

use Illuminate\Validation\Rule;
//...

$request->validate([
    'arr1' => 'required|array',
    'arr2' => 'nullable|array',
    'arr2.*' => [Rule::requiredIf($request->filled('arr1')), 'in_array:arr1.*']
    /...
]);
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way to do it if arr1 is not part of the request?
You can merge your arr1 into $request obj via $request->request->add(['arr1' => ['items']]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.