Search code examples
phplaravellaravel-validation

Laravel - Check name of named error bag


My registration form and login form are on the same page, but in different tabs. By default the active tab is login. While registering if there is any errors, the error messages are returned and I can print the error message at the right place by using named error bag.

The problem is when the error is from the registration form, the active tab should be register. For this I need to check the named of laravel validation.

How can I do that??

COde for validation is:

if ($validator->fails()) {
    return back()
    ->withErrors($validator, 'register')
    ->withInput();
}

Solution

  • You could try using the ->hasBag() method on the $errors variable to check if a bag exists for the given key, which would allow you to output the relevant CSS class or whatever you need to display the correct tab. For example:

    <div class="tab registration{!! $errors->hasBag('register') ? ' active' : '' !!}">
    
    </div>
    

    hasBag('register') will return true if there's an error bag present for the registration form, assuming you've set up your validation to define which bag to use for registration errors. That will allow you to select the correct tab.