我有一个控制器,我想返回一个有多个数组的JSON响应。首先,我将介绍我的控制器:
<?php
public function notificationEmails(Request $request)
{
$shipment = Shipment::findOrFail($request->shipmentID);
$billToAccount = $shipment->billtoAccount;
$billToAccountUsers = $billToAccount->users;
foreach ($billToAccountUsers as $billToAccountUser){
$billToEmail = $billToAccountUser->email;
}
$shipToAccount = $shipment->shiptoAccount;
$shipToAccountUsers = $shipToAccount->users;
foreach ($shipToAccountUsers as $shipToAccountUser){
$shipToEmail = $shipToAccountUser->email;
}
$shipFromAccount = $shipment->shipfromAccount;
$shipFromAccountUsers = $shipFromAccount->users;
foreach ($shipFromAccountUsers as $shipFromAccountUser){
$shipFromEmail = $shipFromAccountUser->email;
}
return response()->json([
'details' => $shipment,
'billersEmails' => $billToEmail
]);
}
这是一个例子,但是此时如果我只是dd($ billToEmail),我将获得所请求的所有数据的多行(所有这些都是电子邮件),但是当我返回特定于JSON的数据时返回“billersEmails”,我只收到其中一封返回的电子邮件。
我知道必须有多封电子邮件被退回,但到目前为止我还没有找到合适的回复。
答案 0 :(得分:1)
您必须使用数组,因为您有多个记录,否则它将覆盖现有值。更改您的代码如下:
<?php
public function notificationEmails(Request $request)
{
$shipment = Shipment::findOrFail($request->shipmentID);
$billToAccount = $shipment->billtoAccount;
$billToAccountUsers = $billToAccount->users;
$billToEmail = array();
$shipToEmail = array();
$shipFromEmail = array();
foreach ($billToAccountUsers as $billToAccountUser){
$billToEmail[] = $billToAccountUser->email;
}
$shipToAccount = $shipment->shiptoAccount;
$shipToAccountUsers = $shipToAccount->users;
foreach ($shipToAccountUsers as $shipToAccountUser){
$shipToEmail[] = $shipToAccountUser->email;
}
$shipFromAccount = $shipment->shipfromAccount;
$shipFromAccountUsers = $shipFromAccount->users;
foreach ($shipFromAccountUsers as $shipFromAccountUser){
$shipFromEmail[] = $shipFromAccountUser->email;
}
return response()->json([
'details' => $shipment,
'billersEmails' => $billToEmail
]);
}