[英]laravel 4 returning validation message error
I am currently just testing laravel 4, but i have a problem, in the laravel docs returning error messages is described this way $messages->first('email');
我目前只是在测试laravel 4,但是我有一个问题,在laravel文档中返回错误消息是这样描述
$messages->first('email');
should return the message, but no matter what methog id try on the messages
i get error 应该返回消息,但无论什么方法尝试
messages
我都会收到错误
my cobtroller 我的cobtroller
public function postSignup()
{
$rules = array(
'display_name' => 'required|unique:users',
);
$messages = array(
'display_name.required' => 'Felhasználónév kötelező',
'display_name.unique' => 'Ez a Felhasználónév foglalt',
);
$val = Validator::make(Input::all(), $rules, $messages);
if ($val->passes())
{
$data = array('msg' => 'yay');
}
else
{
print_r($messages->first('display_name'));
}
return Response::json($data);
}
{"error": {"type":"Symfony\\\\Component\\\\Debug\\\\Exception\\\\FatalErrorException","message":"Call to a member function first() on a non-object"
{“error”:
{"type":"Symfony\\\\Component\\\\Debug\\\\Exception\\\\FatalErrorException","message":"Call to a member function first() on a non-object"
if i try with all
just for a test print_r($messages->all()); 如果我尝试
all
只是为了测试print_r($ messages-> all()); im getting the following 我得到以下
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Call to a member function all() on a non-object"
could please someone point out what i am doing wrong? 可以取悦有人指出我做错了什么?
You may try this 你可以试试这个
if ($val->passes())
{
$data = array('msg' => 'yay');
}
else
{
$messages = $validator->messages();
$data = array('msg' => $messages->first('display_name'));
}
return Response::json($data);
print_r(...);
in the controller
will print the output outside of the template. 在
controller
中将输出模板外部的输出。 On the client side you can check the msg
something like this (using jQuery
for example) 在客户端,您可以检查这样的
msg
(例如使用jQuery
)
$.get('url', function(data){
if(data.msg == 'yay')
{
// success
}
else
{
// failed, so data.msg contains the first error message
}
});
Validator :: make方法只接受两个参数。
You are accessing the messages array you passed into the validator, not the error messages the validator created. 您正在访问传递给验证程序的消息数组,而不是验证程序创建的错误消息。 Change your code to this:
将您的代码更改为:
$val->messages()->first('email')
NOTE: The validator::make method accepts 3 arguments: 注意:validator :: make方法接受3个参数:
/**
* Create a new Validator instance.
*
* @param array $data
* @param array $rules
* @param array $messages
* @return \Illuminate\Validation\Validator
*/
public function make(array $data, array $rules, array $messages = array())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.