max max - 1 year ago 62
PHP Question

Can I re-use validator instance in the controller?

I use AJAX to send my request, and I want to format errors in special way (still JSON though. I want to change data structure of error and add some flags to it)

So since apparently

$this->validate
just would print out errors without my permission! And I have no control over it, I have to use static method of validator

$whitelist = [
'title'=>'required',
'slug'=>'present' ,
'text'=>'present'
];

$validation = Validator::make($request->all(), $whitelist);
if($validation->fails())
{
format_output_likeIwant($validation->messages()->messages());
}

$another_whitelist = [
'some_other_info'=>'required',
];


Just out of curiosity, is there any way for me to validate my
$another_whitelist
with my existing instance? Or should I create a new instance of validator for each list?

By the way, reason for having 2 different validation array is, I'm using this whitelists/arrays to populate my model instance before save/update in database and avoid writing lots of extra code in case of big tables. 2 list here belong to different model/tables (see here for example)

I've looked in the laravel documentation, it seems all of the examples assume single validation list

Answer Source

It sounds like you want to use Validator::after() or Validator::mergeRules(). Check it:

public function index(Request $request)
{
    $mainRules = [
        'title'=>'required',
        'slug'=>'present' ,
        'text'=>'present'
    ];

    /** @var \Illuminate\Validation\Validator $validation */
    $validation = Validator::make($request->all(), $mainRules);

    if ($validation->fails()) {
        //do something
    }

    $additionalRules = [
        'author' => 'required'
    ];
    $validation->mergeRules($additionalRules);

    # validates $mainRules and $additionalRules together...
    dump(($validation->fails()));
}