如何获得$request->;Laravel 5.0


How to get $request->content in Laravel 5.0?

我是Laravel的新手,在获取发布到我正在编写的RESTapi的JSON时遇到了一些困难。

更新为了清楚起见,这个:

    $content = json_decode($request->content);
    var_dump($content);
    exit;

还返回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();
}

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

{
  "name":"Steve Jobs 2",
  "email":"s@trp2.com",
  "password":"something123",
}

以下是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

所以我可以在Request对象中看到content,但无论我尝试什么,它总是空的。所以我的问题是,我到底该如何访问它?!

谢谢!

您可能想要使用$request->getContent()

{
  "name":"Steve Jobs 2",
  "email":"s@trp2.com",
  "password":"something123",
}

不是有效的JSON,因此Laravel无法对其进行解码。

删除此处的尾部逗号[...]ng123",

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

$request->all();
$request->only();
$request->get();

如果您不是以application/json的形式发送请求,请使用$request->json()

Laravel通常会自动解码您的JSON。您可以使用input()检索值:

$user = new User();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = $request->input('password');

还有一种更短的方法,你可以在请求方法上动态访问你的属性:(这可能不适用于某些名称)

$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;

此外,还有其他不错的功能。例如all()only(),它将返回所有输入值的关联数组:

$inputs = $request->all();
// or
$inputs = $request->only('name', 'email', 'password');

作为一个受保护的变量/对象,您需要使用类上预定义的方法来访问它。

您可以使用以下内容。

$request->only('name', 'email', 'password')