Skip to content

Instantly share code, notes, and snippets.

@vistik
Created March 16, 2015 12:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vistik/0da195da9b4441401c15 to your computer and use it in GitHub Desktop.
Save vistik/0da195da9b4441401c15 to your computer and use it in GitHub Desktop.
Laravel 5 - Use form request to validate JSON body
<?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()
);
}
}
Copy link

ghost commented Nov 14, 2017

i simply added this function in form request class

protected function validationData()
{
return $this->json()->all();
}

It worked for me.

@deadenddeveloper
Copy link

// 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