Laravel: validate json object

前提是你 提交于 2019-11-27 23:15:09
Quỳnh Nguyễn

Please try this way

use Validator;

public function store(Request $request)
{
    //$data = $request->all();
    $data = json_decode($request->payload, true);
    $rules = [
        'name' => 'digits:8', //Must be a number and length of value is 8
        'age' => 'digits:8'
    ];

    $validator = Validator::make($data, $rules);
    if ($validator->passes()) {
        //TODO Handle your data
    } else {
        //TODO Handle your error
        dd($validator->errors()->all());
    }
}

digits:value

The field under validation must be numeric and must have an exact length of value.

I see some helpful answers here, just want to add - that my preference is that controller functions only deal with valid requests. So I keep all validation in the request. Laravel injects the request into the controller function after validating all the rules within the request. With one small tweak (or better yet a trait) the standard FormRequest works great for validating json posts.

Client example.js

var data = {first: "Joe", last: "Dohn"};
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST",'//laravel.test/api/endpoint');
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(JSON.stringify(data));

project/routes/api.php

Route::any('endpoint', function (\App\Http\Requests\MyJsonRequest $request){
    dd($request->all());
});

app/Http/Requests/MyJsonRequest.php (as generated by php artisan make:request MyJsonRequest)

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TrafficRequest extends FormRequest{

    public function authorize(){
        return true;//you'll want to secure this
    }

    public function rules(){
        return [
            'first' => 'required',
            'last'  => 'required|max:69',
        ];
    }

    //All normal laravel request/validation stuff until here
    //We want the JSON...
    //so we overload one critical function with SOMETHING LIKE this
    public function all($keys = null){
        if(empty($keys)){
            return parent::json()->all();
        }

        return collect(parent::json()->all())->only($keys)->toArray();
    }
}
rchatburn

Your payload should be payload: { then you can do

$this->validate($request->payload, [
    'name' => 'required|digits:5',
    'age' => 'required|digits:5',
    ]);

or if you are not sending the payload key you can just use $request->all()

Use the Validator factory class instead using validate method derived from controller's trait. It accepts array for the payload, so you need to decode it first

\Validator::make(json_decode($request->payload, true), [
    'name' => 'digits',
    'age' => 'digits',
]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!