how to pass JSON data to view in laravel
20,956
Solution 1
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();
}
}
Solution 2
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'));
Related videos on Youtube

Author by
nouman
Updated on July 05, 2022Comments
-
nouman 6 months
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
-
nouman over 6 yearsits 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); }); }