【问题标题】:Laravel create eloquent object from JSONLaravel 从 JSON 创建 eloquent 对象
【发布时间】:2018-07-18 05:54:46
【问题描述】:

我在客户端有这个 JSON 对象:

我将该 ajax JSON 对象发送到控制器,例如:

$.ajax({
           type: "GET",
           url: url,
           data: {sToken: token.id, reference: r, newserials: jsonObj},
           dataType: "json",
           success: function(data)
           { ... ... etc.

然后在 Controller 我用:

$newserials = $request->newserials;

我现在需要将$newserials 转换为雄辩的对象,所以我想使用$newserials 像:

foreach ($newserials as $new) {

$serial = $new->serial;
$pin = $new->pin;

}

那么我如何才能将 JSON 转换为 eloquent 并以上述方式使用?

该应用程序已上线,我无法对此进行测试,因此我为这些琐碎的问题寻求帮助。对此感到抱歉。

更新: 我以字符串形式发送新闻:

var newserials = JSON.stringify(jsonObj);

其余代码按照您的建议:

$newserials = json_decode(json_encode($request->newserials));

但现在我得到了错误:

试图在 foreach 循环中获取非对象的属性!

【问题讨论】:

标签: php json laravel eloquent


【解决方案1】:

Laravel 自动 json_decodes 来自 json 请求的输入,但它会将对象解码为关联数组而不是对象。如果你真的想要一个对象,你会想要再次编码和解码。

$newserials = json_decode(json_encode($request->newserials));

但是请注意,这只是一个普通的 PHP stdClass 对象,我假设它确实是您所需要的。这不是 Eloquent 模型。

【讨论】:

  • 我将新闻连续剧作为字符串发送,所以我将 var newserials = JSON.stringify(jsonObj); ...现在我在 foreach 循环中遇到错误 - 试图获取非对象的属性...如何解决这个问题,请帮助
  • @AleksPer 您需要使用相关代码更新您的问题。
  • 如图所示:'newserials' => array(array('serial' => 'E1768520/1', 'pin' => 'HRYJ')),
  • @AleksPer 我运行了这段代码$r = array(array('serial' => 'E1768520/1', 'pin' => 'HRYJ')); $newserials = json_decode(json_encode($r)); echo $newserials[0]->serial;,它工作得很好。你能把var_export($request->newserials);放在json_decode之前,把dd($newserials);放在json_decode之后并发布结果吗?
  • @AleksPer 我猜你的错误在其他地方。该输出显示正确的数据。 $newserials 是一个数组。它有一个项目是一个对象,具有正确的属性。您需要在代码中找出错误的来源。
猜你喜欢
  • 2014-08-05
  • 1970-01-01
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 2013-05-20
  • 2021-12-30
相关资源
最近更新 更多