Display different errors based on which submit button has been clicked in Laravel 5.1

- 1 answer

Ad

I hope you're all doing well and having a good festive season. I wanted to post a question to find out how I can display the errors for a particular form in Laravel 5.1 based on what submit button has been clicked. Here is some code to give a better explanation of what I'm trying to do.

<form action="{{ url( '/auth/login' ) }}" id="login" method="post">
    @if (count($errors) > 0)
        <div class="show validation-summary">
            ... display error container only when the login submit button has been clicked
        </div>
    @endif
    <input name="submit" type="submit" value="Login" />
</form>

<form action="{{ url( '/auth/register' ) }}" id="register" method="post">
    @if (count($errors) > 0)
        <div class="show validation-summary">
            ... display error container only when the register submit button has been clicked
        </div>
    @endif
    <input name="submit" type="submit" value="Register" />
</form>

Currently both validation divs are displaying when clicking the Login or Register submit buttons, but I only want to display the validation div which relates to that form that was submitted.

Ad

Answer

Ad

You can use a named error bag.

For example, in your controller you can do:

$validator = Validator::make(Input::all(), [
    'some_input'        => 'required',
], [
    'some_input.required' => 'The input is required.',
]);

// ...some other code may go here

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

To display the errors in your named error bag in the view you can do.

@if(!empty($errors->named_error_bag->first('error_name')))
    {{ $errors->named_error_bag->first('error_name') }}
@endif
Ad
source: stackoverflow.com
Ad