6

How we can return multiple array in json. Suppose we get the following response in Laravel eloquent:

$user= User::all();
$post= Post::all();
$comment= Comment:all();

Now I want to return response in json which include these data:

Response::json(array('user'=>$user,'post'=>$post,'comment'=>$comment));

Using the above method empty value is returned. Any help would be appreciated

Sorry guys. I found the solution. The data that I was passing was already in object form. Therefore I needed to convert it into an array and then pass it.

$user= User::all()->toArray();
$post= Post::all()->toArray();
$comment= Comment:all()->toArray();

Now it will work!

4
  • It looks good, where do you see the Null? Usual issue with JSON is if there is any "echo"s in the method, double check for any debug messages. Commented Feb 11, 2014 at 12:06
  • 1
    Response is like {"user":{},"post":{},"comment":{}}. it's not null but response is showing nothing.Iam getting output when i simple echo these results. Commented Feb 11, 2014 at 12:14
  • debug your data, try switch the $users with a simple array('one', 'two'). Try print_r($post);die; just before the Response::... . Commented Feb 11, 2014 at 12:32
  • Sorry for my stupidity.data that iam passing is already in object form, first i need to convert it into array and then pass it in json_encode.Anyway Thanks for your attention. cheers! Commented Feb 11, 2014 at 12:39

1 Answer 1

21

i think you can try this method:

$user= User::all()->toArray();
$post= Post::all()->toArray();
$comment= Comment:all()->toArray();

Response::json(['user'=>$user,'post'=>$post,'comment'=>$comment]);
Sign up to request clarification or add additional context in comments.

Comments

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.