dongyongju9560 2018-06-04 05:32
浏览 213
已采纳

使用Laravel 5.6 api验证JSON Post

Having a struggle with validating JSON input for an api on Laravel 5.6. I've been trying the solution at How to get and validate application/json data in Laravel? but still doesn't resolve.

The supporting class:

<?php
namespace App\Http\Controllers\API;

class ResponseObject
{
    const status_ok = "OK";
    const status_fail = "FAIL";
    const code_ok = 200;
    const code_failed = 400;
    const code_unauthorized = 403;
    const code_not_found = 404;
    const code_error = 500;

    public $status;
    public $code;
    public $messages = array();
    public $result = array();
}

and the Controller:

namespace App\Http\Controllers\API;

use App\Http\Resources\MyItemsResource;
use App\MyItem;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use \Illuminate\Http\Response;
use \Illuminate\Support\Facades\Response as FacadeResponse;
use \Illuminate\Support\Facades\Validator;
use App\Http\Controllers\API\ResponseObject;



class MyItemsController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $response = new ResponseObject;

        /*
        sending a body of
        {"code": "45678", "description": "My great item"}

        then:
        // print_r($request->json()->all()); die();

        produces:
            Array
            (
                [code] => 45678
                [description] => My great item
            )
         so data is getting to server
        */

        $validator = Validator::make($request->json()->all(), [
            'code', 'required',
            'description', 'required',
        ]);

        if($validator->fails()){
            $response->status = $response::status_failed;
            $response->code = $response::code_failed;
            foreach ($validator->errors()->getMessages() as $item) {
                array_push($response->messages, $item);
            }
        } else {
            $myItem = new MyItem();
            $myItem->code = $request->code;
            $myItem->description = $request->description;
            $response->status = $response::status_ok;
            $response->code = $response::code_ok;
            $response->result = $myItem;
        }

        return FacadeResponse::json($response);
        /*
         Returns:
        {
            "status": "FAILED",
            "code": 400,
            "messages": [
                [
                    "The 1 field is required."
                ],
                [
                    "The 3 field is required."
                ]
            ],
            "result": []
         }
         */
    }
}

Why does it refer to the fields as 1 field and 3 field? What am I missing that it doesn't pick up the fields as they are getting to the controller in the $request?

Any guidance would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • douxidao3524 2018-06-04 05:48
    关注

    It refers to the keys of the validation rules.

    Here you just have an array of 4 words (indexes 1 and 3 are valid rules that fail):

    $validator = Validator::make($request->json()->all(), [
        'code', 'required',
        'description', 'required',
    ]);
    

    ^ This equals to:

    $validator = Validator::make($request->json()->all(), [
        0 => 'code', 
        1 => 'required',
        2 => 'description', 
        3 => 'required',
    ]);
    

    And looks for inputs 0, 1, 2, 3.

    Instead you should make an associative array:

    $validator = Validator::make($request->json()->all(), [
        'code' => 'required',
        'description' => 'required',
    ]);
    

    ^ This will look for inputs code and description and validate them with the rule required

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘