简体   繁体   中英

Return Response()->Json and Arrays in Laravel

I have a controller that I would like to return a JSON response that has multiple arrays. First, I'll present my controller:

<?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
                ]);
}

This is an example, but at this time if I just dd($billToEmail), I will get multiple rows returned of all of the data that I requested (all of which are emails), but when I return the JSON specific return "billersEmails", I only get one of those emails returned.

I know there must be a possibility of the multiple emails being returned, but I haven't found an appropriate response anywhere as of yet.

You have to use array as you have multiple records otherwise it will over-write existing values. change your code as below:

<?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
                ]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM