Laravel信息包错误


Laravel Message Bag Error

我正在为一个项目的时事通讯进行表单验证,新闻信函表单出现在每一页上,所以它也会出现在longin和注册页面上,所以我决定使用Laravel Message Bags来存储新闻信函错误,但它在我检查和输出的实际页面上不断给我一个未定义的属性错误,我不知道我是不是做错了什么,不过这里是细节!

错误:

Undefined property: Illuminate'Support'MessageBag::$newsletter

控制器中的我的代码:

return Redirect::back()->withInput()->withErrors($inputs, "newsletter");

视图中的我的代码:

 @if($errors->newsletter->any())
 <p>
    {{$errors->newsletter->any()}}
 </p>

控制器中的代码:

         $post_data = Input::all();
    $validator = Validator::make(Input::all(),
        array(
            'email' => 'required',
            'password' => 'required'
        ));

    if ($validator->fails()) {
        return Redirect::back()
            ->withInput()
            ->withErrors(['auth-validation' => 'ERROR: in validation!']);
    } 

车辆中的代码:

@if($errors->any())
    @foreach($errors->getMessages() as $this_error)
        <p style="color: red;">{{$this_error[0]}}</p>
    @endforeach
@endif 

RedirectResponse类函数withErrors()没有第二个参数。。

函数vendor'laravel'framework'src'Illuminate'Http'RedirectResponse.php -> withErrors():

/**
 * Flash a container of errors to the session.
 *
 * @param  'Illuminate'Support'Contracts'MessageProviderInterface|array  $provider
 * @return 'Illuminate'Http'RedirectResponse
 */
public function withErrors($provider)
{
    if ($provider instanceof MessageProviderInterface)
    {
        $this->with('errors', $provider->getMessageBag());
    }
    else
    {
        $this->with('errors', new MessageBag((array) $provider));
    }
    return $this;
}

所以,如果你真的想使用MessageBag,那么这应该有效(没有测试它(:

$your_message_bag = new Illuminate'Support'MessageBag;
$your_message_bag->add('foo', 'bar');
return Redirect::back()->withInput()->withErrors($your_message_bag->all());

withErrors应该接收来自验证器对象的消息。在您的验证过程之后,类似于:

  $validation = Validator::make(Input::all(), $validation_rules);
  if (!$validation->passes()){
       return Redirect::back()->withInput()->withErrors($validation->messages());
  }

我希望它对你很好。

您可以编写这样的函数

if(!function_exists('errors_for')) {
 function errors_for($attribute = null, $errors = null) {
    if($errors && $errors->any()) {
        return '<p class="text-danger">'.$errors->first($attribute).'</p>';
    }   
 }
}

然后在你的视图

<div class="form-group">
   <label for="bio">Bio</label>
   <textarea class="form-control" name="bio"></textarea>
</div>
{!! errors_for('bio',$errors) !!}

从Jeffrey Way学习Laracasts