How to send multiple responses for a request in laravel?

Member

by rollin , in category: Third Party Scripts , a month ago

How to send multiple responses for a request in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , a month ago

@rollin 

In Laravel, you can send multiple responses for a request by using a collection or an array to store the responses and then returning that collection or array as the response. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
use IlluminateHttpRequest;
use IlluminateSupportCollection;

public function multipleResponses(Request $request)
{
    $responses = new Collection();

    $response1 = ['status' => 'success', 'message' => 'Response 1'];
    $response2 = ['status' => 'success', 'message' => 'Response 2'];

    $responses->push($response1);
    $responses->push($response2);

    return response()->json($responses);
}


In this example, we first create a new Collection and then add multiple responses to it as arrays. Finally, we return the collection as a JSON response.


You can also use an array instead of a Collection if you prefer. Just make sure to format your responses accordingly and then return the array using response()->json($responses).