I am creating a public API using Laravel 5.2. To keep the code in the controller short, I have created several helper functions, one of which is a function to return a response to the API call, as shown below:
if (! function_exists('buildResponse'))
{
function buildResponse($data)
{
return response()->json($data)->header('foo', 'bar');
}
}
This is how I would call it from the controller:
public function registration()
{
buildResponse(['a' => 'Success']);
}
However this does not work. It only works if I add a return
in front of the function.
public function registration()
{
return buildResponse(['a' => 'Success']);
}
One might say, "Okay, then just include the return
!". The thing is, this particular function will be called by another helper function, for example:
if (! function_exists('throwResponseCode'))
{
/**
* Throws a response code to the client.
* @param $code
* @return mixed
*/
function throwResponseCode($code)
{
switch ($code) {
case '101':
$data[$code] = 'Unable to establish a database connection';
return buildResponse($data);
// Other cases here
}
}
}
Is there any way that I can send a response to the client from the helper function?
Keep it simple bro!
Change
return response()->json($data)->header('foo', 'bar');
To
return response()->json($data)->header('foo', 'bar')->send();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With