Mark
Mark

Reputation: 3197

return validation errors as an array and change to json

I am trying to return my validation errors to angular but I can't figure out how to return them in the format array('field under validation' => 'error message'). This exact array is held in errors->messages() but it is a protected property.

here is my code

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;
    }
}

controller

<?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)
            );
        }
    }
}

this returns the json

{"errors":{}}

if I change the controller to

$errors = $this->calidator->errors()->all();

this is returned

{"errors":["The title field is required.","The focus field is required.","The desc field is required."]}

what I really want returned is

{"errors":[title: "The title field is required.",focus: "The focus field is required.",desc: "The desc field is required."]}

Upvotes: 3

Views: 7042

Answers (1)

Sajan Parikh
Sajan Parikh

Reputation: 4950

The Validator errors in Laravel return a MessageBag object, which has many useful methods you may want to look over.

It sounds like what you want is the toArray method, and you can use it like so in your controller.

Replace the following code that you have in your controller;

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

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

With;

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

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

Or, depending how how you're using it with Angular, you can return the object directly, using the toJson method.

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

Upvotes: 4

Related Questions