laravel将验证错误传递给自定义视图

时间:2016-12-07 14:23:41

标签: laravel laravel-5 laravel-5.2

我创建了一个验证但是无法在视图中显示它,重要的是返回搜索视图并且不重定向回用户。请帮助我,谢谢大家?

控制器:

public function search(Request $request)
{
    $msg = Validator::make($request->all(), [
        'search' => 'required'
    ]);
    if ($msg->fails()) {
        return view('layouts.search')->withErrors($msg->messages());
    } else {
        return "Thank you!";
    }
}

查看:

@if($errors->any())
   <ul class="alert alert-danger">
      @foreach($errors as $error)
         <li> {{$error}} </li>
      @endforeach
   </ul>
@else

1 个答案:

答案 0 :(得分:1)

您可以使用$error->first('name_of_error_field')来显示错误消息。

你可以这样做:

public function search(Request $request)
{
    $validator = Validator::make($request->all(), [
        'search' => 'required'
    ]);
    if ($validator->fails()) {
        return view('layouts.search')->withErrors($validator); // <----- Send the validator here
    } else {
        return "Thank you!";
    }
}

并且在视野中:

@if($errors->any())
   <ul class="alert alert-danger">
      @foreach($errors as $error)
         <li> {{$error->first('name_of_error_field')}} </li>
      @endforeach
   </ul>
@endif
  

详细了解Laravel Custom Validators

希望这有帮助