Home > OS >  Validating a value with an array, Laravel validation. value must be one in the array
Validating a value with an array, Laravel validation. value must be one in the array

Time:11-17

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)]]);

CodePudding user response:

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.

  • Related