1

Now that to get data I call method from controller, that returns data as JSON:

return response()->json([$data]);

Can I add to this response global data? And merge this $data?

For example I have global $user object that I want to give away in each HTTP response to avoid the following entry in each method:

return response()->json(["data" => $data, "user" => $user]);
2
  • could you explain well what you expect to have? an answer has already being given, does it already answer your question? Commented Feb 18, 2017 at 22:16
  • Does one of the given answers answer you question? Commented Feb 19, 2017 at 11:11

2 Answers 2

14

An alternative to @rnj's answer would be to use middleware.

https://laravel.com/docs/5.4/middleware#global-middleware

This would allow you to instead hook in to the request rather than use a helper function that you may decide you don't want/need later.

The handle method for your middleware could look something like:

public function handle($request, Closure $next)
{
    $response = $next($request);

    $content = json_decode($response->content(), true);

    //Check if the response is JSON
    if (json_last_error() == JSON_ERROR_NONE) {

        $response->setContent(array_merge(
            $content,
            [
                //extra data goes here
            ]
        ));

    }

    return $response;
}

Hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

if you are using the json helper ($response->json()) then you need to : setContent(json_encode(array_merge(...)) or else you will have a error referencing the lack of a _toString callable on an array
2

Create your own PHP class or function to wrap Laravel's response with your own data. Eg:

function jsonResponse($data)
{
    return response()->json([
        'user' => $user, 
        'data' => $data,
    ]);
}

Then you can call:

return jsonResponse($data);

This is just a simple example of how to keep your program DRY. If you're creating an application you're expecting to grow and maintain, do something more like this.

3 Comments

@mj could you check my edit. Not sure if it was okay or not because the questions seems a bit unclear.
@OmisakinOluwatobi Yeah, that edit works. It actually makes the encapsulation concept clearer based on the question.
only issue is that if the $user variable is actually as global as being accessible in this function. I hope the Question owner sheds more light...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.