【问题标题】:How to get and validate application/json data in Laravel?如何在 Laravel 中获取和验证应用程序/json 数据?
【发布时间】:2021-08-15 13:13:01
【问题描述】:

我以application/json 内容类型从客户端向服务器发送数据。

然后我尝试在服务器端获取这些信息,例如:

public function register(Request $request)
{

        $data = $request->json()->all();
        var_dump($data); die();
}

它让我空着array()

我还尝试使用以下方法验证传入的 POST:

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

如何在 Laravel 中获取和验证 application/json 数据?

我得到的 POST 数据如下:

dd($_POST);

array:1 [▼
  "application/json" => "{"id":6,"unique_code":null,"name":"О","secondname":"П","lastname":"Валерьевич","datebirth":"14/10/1991 00:00:00","taxcode":"4545","gender":"1","created_at":null,"file":"C:\\db\\tests\\22-07-2017\\MMM1.TXT","orders":{"profession":"Директор","pacient_id":null,"payment":"1","kind_work":"1,2","factory_name":"FALKO","factory_edrpou":"2020","factory_departament":"IT","status_pass":"1","office_address":"Kiev","unique_code":"0","enterprise_id":"12","status":null},"http_code":null}"
]

【问题讨论】:

  • 你检查过请求有没有json数据吗?你能检查一下$request->all()中的内容吗?
  • $request->all() 将为您提供请求有效负载,无论它是 json 还是正常,但要检查它是否是 json 请求,请使用 if ($request->expectsJson()) {...} 然后使用 return response()->json([key=>value])

标签: laravel laravel-5.2 laravel-5.4


【解决方案1】:

我有一个将 json 发布到的 api。我有一个 api 端点,我在其中发布了这个 json

{ "email":"youremail@triumworks.com", "phone": "phone", "name": "name", "password": "password" } 处理请求的相应控制器看起来像

public function create_account(Request $request){
    $data = json_decode(file_get_contents('php://input'));
    $response = new Responseobject;     
    $array_data = (array)$data;

    $validator = Validator::make($array_data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6',
        'phone' => 'required|string|min:12|max:12|unique:users',
    ]);

    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{
        $api_token = str_random(60);
        $user = new User();
        $user->api_token = $api_token;
        $user->name = $data->name;
        $user->email = $data->email;
        $user->phone = $data->phone;
        $user->password = bcrypt($data->password);

        if($user->save()){
            $response->status = $response::status_ok;
            $response->code = $response::code_ok;
            $response->result = $user;
        }           
    }
    return Response::json(
            $response
        );
}

这和上面的一样。

public function create_account(Request $request){
        $response = new Responseobject();

        $validator = Validator::make($request->json()->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
            'phone' => 'required|string|min:12|max:12|unique:users',
        ]);

        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{
            $api_token = str_random(60);
            $user = new User();
            $user->api_token = $api_token;
            $user->name = $data->name;
            $user->email = $data->email;
            $user->phone = $data->phone;
            $user->password = bcrypt($data->password);

            if($user->save()){
                $response->status = $response::status_ok;
                $response->code = $response::code_ok;
                $response->result = $user;
            }           
        }
        return Response::json(
                $response
            );
    }

【讨论】:

  • 如何使用 Laravel 进行验证?
  • 什么是new Responseobject;
  • 我定义的一个类,用于为我的回复提供一般格式。看起来像这样<?php namespace App\Http\Controllers\Api; class Responseobject { const status_ok = "OK"; const status_failed = "FAILED"; 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(); }
  • 它给了我空值:$data = json_decode(file_get_contents('php://input')); //$response = new Responseobject; $array_data = (array)$data;
  • @OPV 你能编辑你的问题以包括整个函数,如果可能的话包括整个班级?
【解决方案2】:

发布的数据最终会出现在请求体参数包中。您可以通过$request->all()$request->request->all() 获取数据。

所以验证器看起来像这样:

$validator = Validator::make($request->all(), []);

深入了解:

或者您可以在控制器中使用validate() 方法。看起来像这样:

$this->validate($request->all(), []);

Laravel docs 中了解更多信息。

为了让事情变得更加复杂,您甚至不需要将 Request 实例注入您的控制器。您可以使用 request() 辅助函数。然后注册方法如下所示:

public function register()
{
    $this->validate(request()->all(), [
        'email' => 'required|email',
        'password' => 'required|min:6|confirmed',
    ]);
}

【讨论】:

  • Nom 它不起作用,因为我有 json 格式的 POST
  • 当我使用 Content-Type: application/json 并通过我的 API(使用 Laravel 构建)发布数据时,上面的示例对我来说非常适用。
  • @OPV $this->validate 自动检查请求是否为json并做出相应响应,你可以检查你自己的方法
  • 你的意思是用这个吗? $validator = Validator::make($request->all(), []?
  • 你能重新格式化你的答案吗,我不明白哪里是正确的解决方案
猜你喜欢
  • 2019-06-10
  • 2018-01-22
  • 2020-12-16
  • 1970-01-01
  • 2018-04-05
  • 2015-01-31
  • 2017-03-15
  • 2020-01-25
  • 2019-12-09
相关资源
最近更新 更多