Created
March 16, 2015 12:06
-
-
Save vistik/0da195da9b4441401c15 to your computer and use it in GitHub Desktop.
Laravel 5 - Use form request to validate JSON body
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace <YourNamespace>\Http\Requests; | |
// To validate the content of the JSON body instead of query params, you need to override the getValidatorInstance() method to create the validator instance with $this->json()->all() instead for $this->all() | |
// This way you can keep your Requests as is and just extend this class instead when you need to validate jsonbody instead of query params | |
abstract class JsonBodyRequest extends Request{ | |
/** | |
* Get the validator instance for the request. | |
* | |
* @return \Illuminate\Validation\Validator | |
*/ | |
protected function getValidatorInstance() | |
{ | |
$factory = $this->container->make('Illuminate\Validation\Factory'); | |
if (method_exists($this, 'validator')) | |
{ | |
return $this->container->call([$this, 'validator'], compact('factory')); | |
} | |
return $factory->make( | |
$this->json()->all(), $this->container->call([$this, 'rules']), $this->messages(), $this->attributes() | |
); | |
} | |
} |
// i created basic class for requests which could get JSON and usual requests.
// maybe it helps somebody
class ApiRequest extends FormRequest
{
protected function validationData()
{
return count($this->json()->all()) ? $this->json()->all() : $this->all();
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i simply added this function in form request class
protected function validationData()
{
return $this->json()->all();
}
It worked for me.