Laravel validation OR

Ian picture Ian · Jan 21, 2016 · Viewed 10.3k times · Source

I have some validation that requires a url or a route to be there but not both.

    $this->validate($request, [
        'name'  =>  'required|max:255',
        'url'   =>  'required_without_all:route|url',
        'route' =>  'required_without_all:url|route',
        'parent_items'=>  'sometimes|required|integer'
    ]);

I have tried using required_without and required_without_all however they both get past the validation and I am not sure why.

route is a rule in the route field

Answer

Saiyan Prince picture Saiyan Prince · Jan 21, 2016

I think you are looking for required_if:

The field under validation must be present if the anotherfield field is equal to any value.

So, the validation rule would be:

$this->validate($request, [
    'name'        =>  'required|max:255',
    'url'         =>  'required_if:route,""',
    'route'       =>  'required_if:url,""',
    'parent_items'=>  'sometimes|required|integer'
]);