Search code examples
laravellaravel-5laravel-validation

How to validate an ID which should be in given array - Laravel


I have an array which is

array (
  0 => 1,
  1 => 7,
  2 => 11,
  3 => 8,
  4 => 5,
) 

Now I want to validate a field status which should be in the given list.

$validation = Validator::make($req->all(),[
    'status.*.id' => 'required'
]);

How can I validate the status? Can anyone suggest any solution? Thank You.


Solution

  • Laravel has an option to validate a value compare to a given array of data:

    //At the top of your class add the correct Rule namespace.
    
    use Illuminate\Validation\Rule;
    
    $yourarray = [
        0 => 1,
        1 => 7,
        2 => 11,
        3 => 8,
        4 => 5,
    ];
    
    $validation = Validator::make($req->all(),[
        'status.*.id' => ['required',Rule::in($yourarray)]
    ]);
    

    For further details follow the official documentation here