无法访问视图中的验证错误

Pok*_*ick 6 php validation blade laravel-4

我已经设置了一个带有一些验证的控制器.

public function attemptLogin()
{
    $rules = array(
        'email'=>'required|email', 
        'password'=>'required'
    );


    $validator = Validator::make(Input::all() , $rules);
    if($validator->fails()){
        return Redirect::to('login')->withErrors($validator);
    };
}
Run Code Online (Sandbox Code Playgroud)

如果我直接在控制器中输出消息

$messages = $validator->messages();
print_R($messages->all());
Run Code Online (Sandbox Code Playgroud)

我收到验证错误 - 但是如果我重定向:

return Redirect::to('login')->withErrors($validator);
Run Code Online (Sandbox Code Playgroud)

$errors视图中可用的数组始终为空.

gia*_*kis 8

来自laravel四个文档

请注意,当验证失败时,我们使用该withErrors方法将Validator实例传递给Redirect .此方法将错误消息刷新到会话,以便它们在下一个请求时可用.

变量$errors它不是一个数组.

$errors变量将是一个实例 MessageBag.

出于某种原因,我不太喜欢@seamlss的想法. 你可以用它 代替.

@if(Session::has('errors'))
<? $errors = Session::get('errors'); ?>
<div class="alert alert-error">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    <ul>
        <li id="form-errors" >
            <h3> {{ $errors->first('email') }}</h3>
        </li>
    </ul>
</div>
@endif
Run Code Online (Sandbox Code Playgroud)

我已经使用了一些bootstrap组件,不要混淆,你唯一需要的是带有花括号的线条和神奇的@符号.

来自laravel docs error-messages-and-views

因此,重要的是要注意,在每个请求中,所有视图中都会始终提供$ errors变量,从而可以方便地假设$ errors变量始终定义并且可以安全使用.

你也可以检查一下

@if( $errors->has('email') )
    <div class="control-group error">
        <label class="control-label" for="email">Email</label>
        <div class="controls">
            <input type="text" id="email" placeholder="Email" name="email">
            <span class="help-inline">{{ $errors->first('email') }}</span>
        </div>
    </div>
@endif
Run Code Online (Sandbox Code Playgroud)


小智 5

我已成功重定向使用 ->withErrors($validation)

然后在视图中检查条件@if( $errors->count() > 0 )......

@if( $errors->count() > 0 )
    <p>The following errors have occurred:</p>

    <ul id="form-errors">
        {{ $errors->first('username', '<li>:message</li>') }}
        {{ $errors->first('password', '<li>:message</li>') }}
        {{ $errors->first('password_confirmation', '<li>:message</li>') }}
    </ul>   
@endif
Run Code Online (Sandbox Code Playgroud)