Ryan Ryan - 2 months ago 9
AngularJS Question

Validating Input::json() in Laravel

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.

Answer

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.