2014-01-10 50 views
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."]} 

回答

0

在Laravel的驗證錯誤返回MessageBag對象,其中有你可能想看看許多有用的方法過度。

這聽起來像你想要的是toArray方法,你可以在你的控制器中使用它。

替換您的控制器中的以下代碼;

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

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

With;

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

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

或者,這取決於你如何是如何使用它的角,可以直接返回對象,使用方法toJson

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

我可以發誓我嘗試過,但它的工作,你是一個傳奇,謝謝你 – Ir1sh

相關問題