Pregunta

Validation does not work with Input::json. Ive tried different ways using json_decode/using arrays but still no luck. Here's my code:

//routes.php
Route::get('create', function() {

    $rules = array(
        'username' => 'required',
        'password' => 'required',
    );

    $input = Input::json();
    //var_dump($input); //outputs std obj with correct inputs
    $validation = Validator::make($input, $rules);
    if ($validation->fails()) { //throws exeption "Call to a member function to_array() on a non-object"
        return Response::json($validation->errors->all());
    }

}

I'm posting the data using Angular Resource...but it always throws an error "Call to a member function to_array() on a non-object"...I cant paste my angular code since I can't format it correctly and stackoverflow doesn't allow me to do that.

¿Fue útil?

Solución

That is because in the input::json() returns an object and validation method expects either array or eloquent object. What you can do is convert the object to an array.

$input = Input::json();
$input_array = (array)$input;

$validation = Validator::make($input_array, $rules);

Updated:

After discussing with @Ryan, I noticed the problem is not from the validation, but in the the response::eloquent() was passed with an array instead of an eloquent object.

Otros consejos

As of [at least] Laravel 5.3, you need to add the ->all() to the answer @Raftalks posted. Here's a shorthand method to automatically throw an exception (422), with all the errors, in one line:

use Validator;
use Input;

... other stuff

Validator::make((array)Input::json()->all(), ["rule"=>"filter"])->validate();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top