Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jvezina's avatar

How to set a different message bag for the validator to use

I need to validate $request on multiple iteration. One iteration identifies critical problems (ie the value is just wrong), and another iteration determines if a value is OK but not acceptable for a special program.

What I want to do is have two different sets of validation rules for each field. When the validator processes one set of rules, it puts the errors in one messagebag. And then the next iteration the validator uses a different messagebag.

How do I specify which messagebag to use on each iteration?

Although if there's a better approach, I'm certainly open to it.

0 likes
3 replies
rodrigo.pedra's avatar

From the docs: https://laravel.com/docs/7.x/validation#automatic-redirection

You may use the validateWithBag method to store the error messages in a named error bag if validation fails:

Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
])->validateWithBag('post');

Also just below: https://laravel.com/docs/7.x/validation#named-error-bags

If you have multiple forms on a single page, you may wish to name the MessageBag of errors, allowing you to retrieve the error messages for a specific form. Pass a name as the second argument to withErrors:

return redirect('register')
            ->withErrors($validator, 'login');

Didn't quite understand your flow description, but think these snippets might help

jvezina's avatar

That's just what I was looking for - except I'm using v5.8 (which I should have mentioned). But it looks like it's available in 5.8 - thanks much!

1 like

Please or to participate in this conversation.