bobD bobD - 1 year ago 79
PHP Question

attaching an error to validator in laravel 5

I'm using

Validator Facade
, here's the code

$req = Request::all();
$rules = [
$validator = Validator::make($req, $rules);

if(/*another problem*/){
// ??

if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();

I want to keep the errors that the Laravel's
make's It self and attach some others to them (If needed).
So for example If there was nothing wrong with the
input but my
statement found an error, the
would fail.

Answer Source

Validator MessageBag

You can add the message to the name property of your form by adding it to the Validator MessageBag.

if(/*another problem*/) {
    $validator->getMessageBag()->add('name', 'Something else does not check out!');

    return redirect()->back()->withErrors($validator)->withInput();

I would recommend doing this logic after you check if the formvalidation has failed, because just adding the message to the MessageBag will not set your validation as failed. Then you can manually return the redirect after one or more of these checks have been done to redirect to the form with errors and input.