如何在Laravel 5.0中获取$ request->内容?

fan*_*tly 1 php laravel-5

我是Laravel的新手,在抓住我正在编写的REST api中发布的JSON时遇到了一些麻烦.

更新 为清楚起见,这:

    $content = json_decode($request->content);
    var_dump($content);
    exit;
Run Code Online (Sandbox Code Playgroud)

也回来了 null

原版的

这是我的store方法:

public function store(Request $request)
{       
    // Creates a new user based on the passed JSON
    // I appreciate this wont work as it's json encoded, but this was my
    // last test. 
    // Previously I'd tried: $content = json_decode($request->content);
    // but that was also null :(
    $user = new User();
    $user->name = $request->content["name"];
    $user->email = $request->content['email'];
    $user->password = $request->content['password'];

    var_dump($request); exit;
    // Commit to the database
    $user->save();
}
Run Code Online (Sandbox Code Playgroud)

这是我试图发送的内容(通过:我只是在休息客户端):

{
  "name":"Steve Jobs 2",
  "email":"s@trp2.com",
  "password":"something123",
}
Run Code Online (Sandbox Code Playgroud)

这是var_dump呈现为响应时的结果:

      protected 'cacheControl' => 
        array (size=0)
          empty
  protected 'content' => string '{
  "name":"Steve Jobs 2",
  "email":"s@trp2.com",
  "password":"something123",
}' (length=85)
  protected 'languages' => null
  protected 'charsets' => null
  protected 'encodings' => null
Run Code Online (Sandbox Code Playgroud)

所以,我可以看到content的范围内Request的对象,但无论我怎么努力,总是空.所以我的问题是,我到底如何访问它?!

谢谢!

rdi*_*diz 7

你可能想用$request->getContent().


Ben*_*rne 6

{
  "name":"Steve Jobs 2",
  "email":"s@trp2.com",
  "password":"something123",
}
Run Code Online (Sandbox Code Playgroud)

是无效的JSON,因此Laravel将无法对其进行解码.

从这里删除尾随逗号 [...]ng123",

然后,您将能够使用上述答案中提到的任何方法,例如(假设您将请求作为application/json发送)

$request->all();
$request->only();
$request->get();
Run Code Online (Sandbox Code Playgroud)

如果您没有将请求作为application/json发送,请使用$ request-> json()