返回响应() - > JSON和阵列中Laravel
我有一个控制器,我想返回具有多个阵列的JSON响应。首先,我将介绍我的控制器:返回响应() - > JSON和阵列中Laravel
<?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”时,我只收到其中一封邮件。
我知道一定有返回的多个电子邮件的可能性,但我还没有找到一个合适的响应作为尚未在任何地方。
回答:
你必须使用数组,你有多个记录否则会覆写现有值。改变你的代码如下:
<?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
]);
}
以上是 返回响应() - > JSON和阵列中Laravel 的全部内容, 来源链接: utcz.com/qa/260834.html