laravel 5验证消息返回一些数组

时间:2015-10-05 04:28:09

标签: php laravel laravel-5

我在laravel中进行验证,所以下面是我的代码

//error holder
                $error = array();
                $validator = Validator::make($request->all(),[
                    'email' => 'email|unique:users',
                    'username' => 'required|regex:/^[a-zA-Z0-9_]+([-.][a-zA-Z0-9_]+)*$/',
                    'new_password' => 'required',
                    'confirm_password' => 'required',
                    'full_name' => 'required',
                    'role' => 'required',
                    'status' => 'required',
                ]);
                if ($validator->fails()){ 
                    array_push($error, $validator->messages());
                }
$msg = "Ops seems like there's an error: ";
                    foreach($error as $error_bug){
                        $msg .= $error_bug . ", ";
                    }

//return error
return $msg;

所以首先我创建了一个空数组,然后将错误消息推送到数组并循环遍历对象数组并将其返回给客户端。一切都有效,除了那个丑陋的事情,它让我这个

  

Ops似乎有错误:{"电子邮件":["电子邮件已被删除。"]}

因为你可以看到我不想要的括号和括号,我只想从验证中得到错误信息失败。任何想法,帮助?

1 个答案:

答案 0 :(得分:1)

@if (count($errors) > 0) <div class="alert alert-danger">
<ul> @foreach ($errors->all() as $error)
<li><b>Ops, something went wrong.</b></li>
<li>{{ $error }}</li>
@endforeach
</ul> </div> @endif

此方法的优点是您不会重复不必要的代码。

更新:

$msg = $validator->errors()->all("Ops seems like there's an error: :message");