How to display error separately on Laravel

时间:2016-04-04 17:07:04

标签: php laravel laravel-4

I clicked on login, but the right side of register the errors shows up.

enter image description here

this is my view

<!-- REGISTER AREA LEFT SIDE -->
<div class="col-md-6">
    <h3>Member Login</h3>
    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form role="form" method="POST" action="{{ URL::route('login') }}">
        ....
</div>

<!-- REGISTER AREA RIGHT SIDE -->
<div class="col-md-6">
    <h3>Member Registration</h3>
    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form role="form" method="POST" action="{{ URL::route('register') }}">
        ....
</div>  

and this is my controller return

return Redirect::back()
    ->withInput()
    ->withErrors($validation);

any way to rename the error with login_error and register_error? how to separate them into two variables, cause it conflict and shows both message on right side.

1 个答案:

答案 0 :(得分:0)

您的字段在html中有名称,并且laravel将错误绑定到它们的名称,以便您可以显示特定字段的错误,因此您可以使用以下内容包装登录表单错误块:

@if($errors->first('login_email') || $errors->first('login_password'))
// ...
@endif

和注册表单错误块:

@if($errors->first('register_email') || $errors->first('register_password') || $errors->first('register_password_bis'))
// ...
@endif

这可能不是最好的解决方案,但我知道它有效并且可以避免使用黑客攻击。此外,它没有添加太多的样板,因为那里没有很多字段。

根据您构建构建器的方式,您还可以在会话中flash a message告诉您查看您验证的表单:

登录

@if (count($errors) > 0 && Session::has('validated_login_form') == true)
// ...
@endif

注册

@if (count($errors) > 0 && Session::has('validated_registration_form') == true)
// ...
@endif   

另一种方法是查看withErrors($validation)函数在Laravel源代码中是如何工作的,看看你是否可以自己重现它,但是根据你刚刚验证的形式命名$ errors会有所不同。