how to pass JSON data to view in laravel - json

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

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();
}
}

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

loop though json response laravel 5.6

How can i loop though an json response?
I need to loop though eg. $request->device_id.
Then i could save each value returned. (I need to loop though most of the requests).
return response()->json([
'data' => Device::create([
'device_id' => $request->device_id,
'hub_id' => $request->hub_id,
'name' => $request->name,
....
]),
]);
json response looks like:
According to Laravel documentation
When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to dig into JSON arrays:
$name = $request->input('user.name');
however you can use json_decode() function to convert JSON to PHP array. then loop through the array using foreach()
Suppose you have store all the devices into variable name $devices.
$devices = Device::all();
foreach($devices as $device) {
$deviceIds = json_decode($device->devicez_id);
foreach($deviceIds as $deviceId) {
//you will get device id on variable name (deviceId)
}
}

reverse of toJson() - deserialise JSON to models

I load models with relations (like a book, authors, publisher, keywords) and send it out to the web interface in JSON. Users will edit it there, and then the interface will send it back as JSON. The question is how do I create a model from the JSON (the opposite of toJson() call) and then save it to the database. It would also be helpful if I could compare the original data - reloaded from the db again - with the data I receive from the web layer.
You can decode the JSON once it's received by the server:
$decoded = json_decode( Input::get('json') );
If you want to compare the models one option is grabbing the ID of the model from your decoded JSON (make sure you double check the user has access to it in case they try fudging the data on you), loop over your key/values for your decoded data and match them against each other.
$model = YourModel::find( $decoded->id ); // dont forget to ensure they have access to this model
// Set up an empty array to store anything that's changed
$changes = array();
// Loop over your decoded values
foreach( $decoded as $key => $value ) {
// If the value in your model doesn't match the decoded value, add to the changes array
if( $model->{$key} != $value ) {
$changes[$key] = $value;
}
}
you can convert it to a collection by using collect(json_decode($json)).
collection Docs

Symfony2 - FOSRestBundle - Custom Serializer or JSON Output

How do you create a custom JSON output with FOSRestBundle?
The code already has methods which are used to convert entities and paginated result sets to JSON. As well as generate unique URLs to view/edit the entities in the outputted JSON.
How can these be used with FOSRestBundle?
Example of custom method to convert Bars to JSON output:
$json = $this->getJsonFactory('Bar')
->dataTableFormat($data);
return $this->jsonResponse($json);
How can this custom method be used as the output for JSON from view?
$data = $this->getDoctrine()->getRepository('Foo:Bar')
->findAll();
$view = $this->view($data, 200)
->setTemplate("Foo:Bar:index.html.twig")
->setTemplateVar('bars')
;
JMSSerializerBundle is available if it helps.
Using custom handlers this is possible, see docs: http://symfony.com/doc/master/bundles/FOSRestBundle/2-the-view-layer.html#custom-handler
Working example:
$handler = $this->get('fos_rest.view_handler');
if (!$handler->isFormatTemplating($view->getFormat())) {
$templatingHandler = function ($handler, $view, $request) {
$data = $this->getJsonFactory('Bar')
->dataTableFormat($$view->getData());
$view->setData($data);
return $handler->createResponse($view, $request, 'json');
};
$handler->registerHandler('json', $templatingHandler);
}
The $templatingHandler method handles calling the JsonFactory and setting the formatting of data for json output.

How to access values in a multidimensional JSON array from backgrid template

I am trying to get json value from laravel json response to Backgrid template
My laravel json response is
return Response::json(
array(
'items'=> $articles->toArray()
));
It response json array like these
{"items":[{"id":30,"title":"Tester","body":"tesrter","user_id":566,"user_nickname_id":0,"category_id":1,"community_id":0,"ref_link":"face.com","status":3,"points":0,"editor_id":566,"created_at":"2015-03-21 15:53:43","updated_at":"2015-03-21 09:23:43","category":{"id":1,"name":"Cupcake wrappers","description":"","created_to":"2015-02-27 13:53:15","updated_to":"0000-00-00 00:00:00"}}]}
My backgrid cell is
var CateoryType = Backgrid.Cell.extend({
template: _.template('<%=category.name%>'),
render: function () {
this.$el.html(this.template( this.model.toJSON() ));
this.delegateEvents();
return this;
}});
But I couldn't get category 's name from json response.
How Could I get Category name from my Backgrid Cell or any other way to access it?
the problem being you are not returning an exact collection from your laravel, you can do it in either using backbone or laravel(optimal)
instead return just say
echo json_encode($articles->toArray());
Using backbone parse method:
in your collection use
parse : function(response){
return response.items
}

zf2 How to save json return value to a variable

i have this code to return json
return new JsonModel(array(
'id' => $id,
'name' => 'ana',
));
that code will return this
{"id":"83493","name":"ana"}
my question is how do i save id value to a variable. lets just say my variable is $a. How do i save 83493 to $a?
I assume you are returning the json array from a controller's action to a view file.
Was this action called via some ajax call? If yes then, on success of that ajax call, you will have something as -
$.ajax({
.....
.....
.....
success: function(data) {
var a = data.id; //Here variable a will have value as 83493
},
});
As you are sending the array and not just a single value, the data parameter in the success function will act like a object and so id and name will become its properties.
Properties should be accessed via dot (.) operator Eg: data.id and data.name
I hope this is what you are expecting, please let us know if its not.