Combine multiple validators so they return all errors

Submitted by The Saint Genius - 2 years ago

When validating data belonging to multiple models you might be missing errors if you run your validators one by one. This simple trick combines validators and their errors.

// Get input
$firstData = Input::get('first');
$secondData = Input::get('second');

// Spawn Validators
$firstValidator = Validator::make($firstData, First::$rules);
$secondValidator = Validator::make($secondData, First::$rules);

// Run validators, return errors on fail()
if($firstValidator->fails() || $secondValidator->fails()){
	$errors = $firstValidator->messages()->merge($secondValidator->messages());

	return Redirect::route('route.to.return.to')
		->withErrors($errors);
}

Ads cover the costs of maintaining Laravel-tricks

comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks