【问题标题】:return validation errors as an array and change to json将验证错误作为数组返回并更改为 json
【发布时间】:2014-01-10 13:53:44
【问题描述】:

我正在尝试将我的验证错误返回到 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;
    }
}

控制器

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

【问题讨论】:

    标签: php json laravel-4


    【解决方案1】:

    Laravel 中的 Validator 错误返回一个 MessageBag 对象,它有很多有用的方法你可能想看看。

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

    替换控制器中的以下代码;

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

    有;

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-18
      • 1970-01-01
      • 2019-01-27
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      相关资源
      最近更新 更多