Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel validate Content-Type: application/json request

in laravel 5 i made a new request named ApiRequest.

class ApiRequest extends Request
{
    public function authorize() {
      return $this->isJson();
    }
    public function rules()
    {
     return [
            //
            ];
    }
}

As you can see i am accepting only json data. And i am receiving the json in controller like this

public function postDoitApi(ApiRequest $payload) {
        $inputJson = json_decode($payload->getContent()); 
        $name = $inputJson->name;
}

Which is working fine. I am getting data in $name. But now i need to validate the input json. I need to set validation rule in ApiRequest for the name key like this

public function rules()
{
     return [
            'name' => 'required|min:6'
            ];
}

Help me to do this. Thanks.

like image 435
Sudipta Dhara Avatar asked Jul 29 '15 11:07

Sudipta Dhara


2 Answers

Laravel validates AJAX requests the same way. Just make sure you're setting one of these request headers on your request:

'Accept': 'application/json'

'X-Requested-With': 'XMLHttpRequest'

like image 81
Kestutis Avatar answered Sep 19 '22 15:09

Kestutis


Validating any headers can be done in clean way two steps:

Step 1: Prepare header data to request data in prepareForValidation method.
public function prepareForValidation()
{
    $this->merge([
        "content_type" => $this->headers->get("Content-type"),
    ]);
}
Step 2: Apply any validation rules that you want, (Here, you want your data exact to be application/json. so
public function rules(): array
{
    return [
        "content_type" => "required|in:application/json",
    ];
}

Complete Example looks like:

/**
 * Class LoginRequest
 *
 * @package App\Requests
 */
class LoginRequest extends FormRequest
{
    public function prepareForValidation()
    {
        $this->merge([
            "content_type" => $this->headers->get("Content-type"),
        ]);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            "content_type" => "required|in:application/json",
        ];
    }
}
like image 41
Bedram Tamang Avatar answered Sep 22 '22 15:09

Bedram Tamang