Php 将验证错误作为数组返回并更改为json

Php 将验证错误作为数组返回并更改为json,php,json,laravel-4,Php,Json,Laravel 4,我试图将我的验证错误返回到angular,但我不知道如何在格式数组中返回它们(“验证下的字段”=>“错误消息”)。此确切数组保存在errors->messages()中,但它是受保护的属性 这是我的密码 validator.php <?php namespace TrainerCompare\Services\Validation; use Validator as V; /** * */ abstract class Validator { protected $error

我试图将我的验证错误返回到angular,但我不知道如何在格式数组中返回它们(“验证下的字段”=>“错误消息”)。此确切数组保存在errors->messages()中,但它是受保护的属性

这是我的密码

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;
    }
}
如果我将控制器更改为

$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."]}

Laravel中的验证器错误返回一个对象,其中有许多有用的方法,您可能需要查看

听起来您想要的是
toArray
方法,您可以在控制器中这样使用它

替换控制器中的以下代码

$errors = $this->validator->errors();

return Response::json(
    array('errors' => $errors)
);

或者,根据您对Angular的使用方式,您可以使用
toJson
方法直接返回对象

return $this->validator->errors()->toJson();
$errors = $this->validator->errors();

return Response::json(
    array('errors' => $errors)
);
$errors = $this->validator->errors()->toArray();

return Response::json(
    array('errors' => $errors)
);
return $this->validator->errors()->toJson();