如何从Laravel中请求的一个参数中获取JSON

How to get JSON from one parameter of request in Laravel

我想将字符串化的 JSON 发送到 API 请求的字段之一,如下所示:

解码:

https://api.some.com/foo/bar?a=788&b=My Name&c=[{"name":"pejman"},{"Some":"thing"}]

我想使用 $request->c 获取 c 参数,但我想在我的控制器中自动将其作为解码 JSON 获取。

这是我的PHP代码

MyRequest.php:

<?php

use InfyOm\Generator\Request\APIRequest;

class MyRequest extends APIRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'a' => 'required',
            'b' => 'required',
            'c' => 'requried',
        ];
    }
}

SomeController.php:

<?php

class SomeController extends Controller
{

    public function store(MyRequest $request)
    {
        $c = $request->c;
        $c = $request->json('c');
        $c = $request->json()->all();
    }

}

I want $c to be a JSON decoded automatically in my controller, How can I do that? Is that event possible to do this using MyReqest and how?

您可以使用 Illuminate\Validation\ValidatesWhenResolvedTrait 中的 prepareForValidation() 方法操作请求数据。所以,在你的 MyRequest class:

中实现这个方法
protected function prepareForValidation()
{
    $this->merge([
        'c' => json_decode($this->c),
    ]);
}