0
我想将我的验证错误返回给角度,但我无法弄清楚如何将它们返回格式数组('验证下的字段'=>'错误消息' )。这个确切的数组保存在errors-> messages()中,但它是一个受保护的属性。作为数组返回验证错误并更改为json
这里是我的代码
validator.php
<?php namespace TrainerCompare\Services\Validation;
use Validator as V;
/**
*
*/
abstract class Validator
{
protected $errors;
public function validate($data)
{
$validator = V::make($data, static::$rules);
if ($validator->fails()) {
$this->errors = $validator->messages();
return false;
}
return true;
}
public function errors()
{
return $this->errors;
}
}
控制器
<?php
use TrainerCompare\Services\Validation\ProgramValidator;
class ProgramsController extends BaseController
{
protected $program;
protected $validator;
public function __construct(Program $program, ProgramValidator $validator)
{
$this->program = $program;
$this->validator = $validator;
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
$input = Input::all();
$v = $this->validator->validate($input);
if ($v == true) {
//$this->program->create($input);
return Response::json(
array('success' => true)
);
} else {
$errors = $this->validator->errors();
return Response::json(
array('errors' => $errors)
);
}
}
}
这个返回JSON
{"errors":{}}
如果我控制器更改为
$errors = $this->calidator->errors()->all();
这个返回
{"errors":["The title field is required.","The focus field is required.","The desc field is required."]}
我真正想要返回的
{"errors":[title: "The title field is required.",focus: "The focus field is required.",desc: "The desc field is required."]}
我可以发誓我尝试过,但它的工作,你是一个传奇,谢谢你 – Ir1sh