4

I want to pass this JSON data to some view but don't know how its works.

I have used, make view also, and convert this data to JSON and pass other way but it didn't work

$items = Items::all();
return response()->JSON($items);

e.g view is items.create

2
  • open chrome dev tools, go to network tab, make the request and inspect the response. also post more code i.e routes. Commented Sep 3, 2016 at 18:22
  • for passing to the view: $items = Items::all(); return view('items.create', compact('items')); for getting json data only : $items = Items::all(); return $items; Commented Sep 4, 2016 at 3:07

2 Answers 2

3

If you want to create JSON response, you need to convert collection to an array:

$items = Items::all()->toArray(); // $items is array now
return response()->json($items);

If you want to pass some JSON data to a view, do this:

$items = Items::all()->toJson();
return view('items.create', compact('items'));
Sign up to request clarification or add additional context in comments.

1 Comment

its not showing anything in console , i'm working with angular JS here is the code $scope.init = function() { $http({ method : 'GET', url : 'http://localhost:8000/item' }) .success(function(data) { console.log(data); }); }
3

For Laravel ver 4.2, You can pass your data to your blade view with a variable (eg:$data) having an array which will be used in your blade.

$flag is variable being used in the JS part of your code, so you can pass that also as an array: Response::json(['param1' => $foo1, 'param2' =>$foo2)]);

In your controller return the view:

 return Response::json(['view' => View::make('yourbladename', $data)->render(), 'flag'=>$flag]);

In your JS use the data variables as:

function(data){     
 $('#DivToAppendHTML').append(data.view);                    //this appends html blade to the Div having the ID DivToAppendHTML
       if(data.flag == 1){                                  //this uses the second variable passed in controller for any other purpose
                       $('.classname').remove();
        }
}

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.