0

I have to write validation rule that should verify if address is unique on rows where routing_id has given value. That is simple. But in some cases routing_id field may be NULL and then my validation request rule doesn't work.

Here is my rule:

$rules['address']   = 'required|ip|unique:vias,address'.\Route::current()->getParameter('via')->id.',id,routing_id,'.request()->input('routing_id'));

When I am patching row with null as routing_id in my POST array I want my address to be unique within all rows with nulled routing_id field. But it does not work.

And my question is: how to solve it?

piotr
  • 1,282
  • 1
  • 8
  • 20
  • Why did you concat this: `address'.\Route::current()->getParameter('via')->id.'` secondly are you using L5.4? – Emeka Mbah Jul 12 '17 at 09:27
  • unique rule needs: table (`vias`), column (`address`), id to be ignored when patching ( `\Route::current()->getParameter('via')->id`), name of id column (`id`) and then additional where conditions: so i have: where `routing_id` equals given `routing_id` post value. (project has been built using L5.3 and I didn't update it to 5.4 yet) – piotr Jul 12 '17 at 09:32
  • Remember: unique:table,column,except,idColumn In that case should look this way: `$routing_id = \Route::current()->getParameter('via')->id; "required|ip|unique:vias,address,{$routing_id},routing_id"` – Emeka Mbah Jul 12 '17 at 09:38
  • You dont get it. `routing_id` IS NOT my `id` column. I need to have unique `address` value where `routing_id` is null or have any other value. It works properly when `routing_id` has any value other than NULL. – piotr Jul 12 '17 at 09:43

2 Answers2

0

After couple of hours of research I finally found where the problem was.

By using Store Request Validation implemented in Laravel I can modify POSTed parameters. In my validation rule posted above I had

request()->input('routing_id')

which was retrieving FRESH copy of request params, not these modified by me. That is why my NULL values wasn't used - cause I was conditionally merging some special values with NULL value.

Params was properly changed, but only inside StoreRequestValidation class.

piotr
  • 1,282
  • 1
  • 8
  • 20
0

you can first check if address!=null then do validate like these code

$this->validate($request,
            [
                'name' => 'required|max:50',
                'lastname' => 'required|max:50',
                'city_id' => 'required',
                'avatar' => 'mimes:jpeg,bmp,png,jpg'
            ]);

        if(isset($request->address))
        {
            $this->validate($request,
                [
                    'address' => 'required|max:150|email|unique:users'
                ]);
        }
Mahdi mehrabi
  • 1,486
  • 2
  • 18
  • 21