Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - return response from helper

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?

like image 510
baskoros Avatar asked Sep 19 '25 01:09

baskoros


1 Answers

Keep it simple bro!

Change

 return response()->json($data)->header('foo', 'bar');

To

 return response()->json($data)->header('foo', 'bar')->send();
like image 73
KmasterYC Avatar answered Sep 21 '25 15:09

KmasterYC