How can I add condition based on the parameters of the array data on the rules Laravel?

瘦欲@ 提交于 2019-12-24 20:02:22

问题


I use Laravel 5.3

My rules Laravel like this :

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AddCartRequest extends FormRequest
{
    public function rules()
    {
        return [
            'product_id'=>'required|numeric',
            'delivery_address'=>'required',
            'request_delivery_at' => 'required|date_format:d-m-Y H:i:s|after:120 minutes'
        ];
    }
}

The result of echo '<pre>';print_r($this->request->get('delivery_address'));echo '</pre>'; like this :

Array
(
    [sender_name] => chelsea
    [postal] => 12345
    [country] => japan
    [city] => tokyo
    [send_date] => 09-12-2017
    [send_time] => 
    [information] => test
)

I want to make it like this :

If send_time is empty, the rules of request_delivery_at like this :

'request_delivery_at' => 'required|date_format:d-m-Y H:i:s'

So, it without |after:120 minutes

If send_time is have value (for example send_time = 12:30:00), the rules of request_delivery_at like this :

'request_delivery_at' => 'required|date_format:d-m-Y H:i:s|after:120 minutes'

How can I do it?

Update :

I try like this :

public function rules()
{
    $send_time = $this->request->get('delivery_address')['send_time'];

    if($send_time)
        $validation_time = '|after:120 minutes';
    else
        $validation_time = '';  

    return [
        'product_id'=>'required|numeric',
        'delivery_address'=>'required',
        'request_delivery_at' => 'required|date_format:d-m-Y H:i:s'.$validation_time
    ];
}

Seems it works


回答1:


Your question is not very clear for me, so far to what i understand is, you want to have conditional validation rule, based on the send time in delivery address array's presence,

you can achieve this by creating your own validation rule or by adding validations checking conditionally in the controller it self,

controller method ex:

if(!$request->has('delivery_address.send_time')){
    $rules = [

    ];

    $messages = [


    ];

    $validator = Validator::make($request->all(),$rules,$messages);
    if($validator->fails()){
        $this->throwValidationException($request,$validator);
    }
}else{
  $rules = [

    ];

    $messages = [


    ];

    $validator = Validator::make($request->all(),$rules,$messages);
    if($validator->fails()){
        $this->throwValidationException($request,$validator);
    }

}

or you can refer the following my SO answer on how to make custom validation rule. Date Compare in validation Laravel 5.2



来源:https://stackoverflow.com/questions/47726407/how-can-i-add-condition-based-on-the-parameters-of-the-array-data-on-the-rules-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!