1

I am trying to validate a value by checking the value is in an array, this is what I have so far:

$agency_names = Session::get('config.agency-names');
$request->validate([
   'agency-name' => 'required|array:' . $agency_names . ''
]);

$agency_names (output):

0:
  AgencyID: "A1169"
  AgencyName: "19 London"
  AgencyType: "Agency Plus"

1:
  AgencyID: "A1095"
  AgencyName: "Abbeville Nannies"
  AgencyType: "Affiliate"

Any help would be appreciated.

Updated code:

$agencies = Session::get('config.agency-names');

$names = array_map(fn($agency_data): string => $agency_data->AgencyName, $agencies);

$request->validate(['agency-name' => 'required', Rule::in($names)]);

Updated code (resolved)

$agencies = Session::get('config.agency-names');
    $agency_names = array();
    for ($x = 0; $x < count($agencies['Agencies']); $x++) {
        $name = $agencies['Agencies'][$x]["AgencyName"];
        array_push($agency_names, $name);
    }

$request->validate(['agency-name' => ['required_if:referral,no', Rule::in($agency_names)]]);

1 Answer 1

2

Check out the documentation on Laravel validaion rules, specifically the in rule.

Assuming $agency_names is an array, you can do this:

use Illuminate\Validation\Rule;

...

$request->validate([
  'agency-name' => [
    'required',
    Rule::in($agency_names),
]);

PS. Seeing the structure of your $agency_names array, you should map it first with $names = array_map(fn($agency_data): string => $agency_data->AgencyName, $agency_names);. I also suggest renaming $agency_names to $agencies, because the variable name is misleading.

Sign up to request clarification or add additional context in comments.

11 Comments

Thanks, I am getting this error now 'ErrorException Array to string conversion' I have tried using the implode method tho convert the array to a string but still get the same error.
so.. agency-name is an array? can you give an example of what it might contain? and what is $agency_names?
I have added the JSON for the $agency_names array. I tried looping the array and pushing the 'AgencyName' value into a separate array to use instead.
please add it to your original post, not to my answer.
and i saw your edit added an example for $agency_names but you still didn't answer what is the type of the incoming agency-name and an example for that. in my answer i assumed it to be a string, like the variable name suggests, but i think you might be using an array, hence the error.
|

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.