简体   繁体   中英

$request->json()->all() return empty Laravel

Why my request becomes empty when i use $request->json()->all(), below my code:

$request = new \Illuminate\Http\Request();
$request->setMethod('POST');
$request->query->add(['foo' => 'bar']);
$postData = $request->json()->all();

dd($postData);

The result is:

[]

To add parameters to a request object use add() like this:

$request = new \Illuminate\Http\Request();
$request->setMethod('POST');

// single items 'test' and '123'
$request->request->add(['test', '123']);

// $key => value
$request->request->add(['test' => '123']); 
 
$postData = $request->all();

dd($postData);

The output is then something like this:

array:3 [▼
  0 => "test"
  1 => "123"
  "test" => "123"
]

$request->json() gets the content of the request ( Laravel docs ) as json - which is NULL in your case.

You can run dd($request) and see:

Illuminate\Http\Request {#1796 ▼
  #json: null
  #convertedFiles: []
  #userResolver: null
  #routeResolver: null
  +attributes: Symfony\Component\HttpFoundation\ParameterBag {#1798 ▼
    #parameters: array:1 [▼
      "test" => "123"
    ]
  }
  +request: Symfony\Component\HttpFoundation\ParameterBag {#1795 ▼
    #parameters: array:3 [▼
      0 => "test"
      1 => "123"
      "test" => "123"
    ]
  }
  +query: Symfony\Component\HttpFoundation\InputBag {#1797 ▶}
  +server: Symfony\Component\HttpFoundation\ServerBag {#1779 ▶}
  +files: Symfony\Component\HttpFoundation\FileBag {#1791 ▶}
  +cookies: Symfony\Component\HttpFoundation\InputBag {#1794 ▶}
  +headers: Symfony\Component\HttpFoundation\HeaderBag {#1778 ▶}
  #content: null
  #languages: null
  #charsets: null
  #encodings: null
  #acceptableContentTypes: null
  #pathInfo: null
  #requestUri: null
  #baseUrl: null
  #basePath: null
  #method: null
  #format: null
  #session: null
  #locale: null
  #defaultLocale: "en"
  -preferredFormat: null
  -isHostValid: true
  -isForwardedValid: true
  -isSafeContentPreferred: null
  pathInfo: "/"
  requestUri: ""
  baseUrl: ""
  basePath: ""
  method: "POST"
  format: "html"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM