How to show json data in laravel - laravel

i have json array from return $data->group, here the result:
[{
"id": 2,
"name": "Grup 1",
"created_at": "2016-03-16 02:09:15",
"updated_at": "2016-03-16 02:09:15",
"pivot": {
"cabang_id": 28,
"group_id": 2
}}]
i want to "id" and "name" from this data.
i have tried using $data->group->id and $data->group->name but error Undefined property: Illuminate\Database\Eloquent\Collection::$id
how can i take from $data->group?

If you consider the error:
Undefined property: Illuminate\Database\Eloquent\Collection::$id
Then it shows that you're dealing with a Collection object. You can access a Collection's attribute's using the get('key') method as user Alexy Mezenin mentioned.
So you would do something like this in your case:
$data->group->get('id')
Check the docs/api for further details:
Docs: https://laravel.com/docs/5.2/collections#method-get
Api: https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Collection.html#method_get
Normally you can make use of an Eloquent model's magic methods to access its attributes directly by their key name as you were trying to do in the code sample you gave, i.e. $data->group->id. I believe this isn't working for you because you've already returned the data as json, if you would access the object before returning it as json then you would probably be able to access the attributes using the magic methods.

Try to use ->get('id') on the object with json data. Or $request->input('id') where $request is your Request object.

Related

The filtered result I get by running the filter method on a laravel collection returns a new collection with an undesired index

To make it easier to understand the problem, I will hardcode the data that I am using the collection on and explain the problem.
Let us assume the following data structure in JSON format,
{
"shelters_with_linear_distances": [
{
"id": 3,
"shelterName": "Third Shelter",
"latitude": "5.0034000",
"longitude": "70.1230000",
"linear_distance": 3.1352984845527
},
{
"id": 4,
"shelterName": "Fourth Shelter",
"latitude": "5.1413000",
"longitude": "70.2250000",
"linear_distance": 2.7850629146201
},
{
"id": 5,
"shelterName": "Fifth Shelter",
"latitude": "5.2220000",
"longitude": "70.1320000",
"linear_distance": 2.6042789457753
}
]
}
The following filter method is run on a collection format of 'shelters_with_linear_distance' in the above data structure and $minimum_distance_to_a_shelter is a dynamically calculated value that holds a data type of double.
$nearest_shelter = $shelters_with_linear_distances_from_user
->filter(function ($shelter, $key) use ($minimum_distance_to_a_shelter) {
return $shelter['linear_distance'] == $minimum_distance_to_a_shelter;
});
The problem here is if I send back the value returned by the filter method (which is the $nearest_shelter) as JSON to the frontend,
in the postman I see the following output,
{
"nearest_shelter": {
"2": { // <------------------------------------ I can not figure out from where this key '2' is coming from.
"id": 5,
"shelterName": "Fifth Shelter",
"latitude": "5.2220000",
"longitude": "70.1320000",
"linear_distance": 2.6042789457753
}
}
}
The problem is I can not figure out from where the key I have pointed with an arrow in the above line of code is coming from.
*) It is okay if that value '2' never changes so that in the later parts of code I can always access the $nearest_shelter as $nearest_shelter['2']. But the problem is, the value of that key changes depending on the data I am receiving from the db.
One time that value of the key was '1', then once I added some new records to the db it was '2'. Also this one other time there was no key marked as either '1' or '2' and the shelter I wanted was directly inside the collection.
Can someone please help me understand why this is happening and how to get rid of that since I want to access the value inside the $nearest_shelter in latter parts of the code and I do not want to get a key like that which I do not know the value of beforehand to access the $nearest_shelter later in the code.
(Project I am working on uses laravel 5.2)
Thanks.
When you filter a collection, the index is preserved.
The "2" is because this element was the third (so index 2) in your original collection.
To fix this, just add ->values() after the filter:
$nearest_shelter = $shelters_with_linear_distances_from_user
->filter(function ($shelter, $key) use ($minimum_distance_to_a_shelter) {
return $shelter['linear_distance'] == $minimum_distance_to_a_shelter;
})->values();
This way the index will be reset and will start from 0, as usual.
From the documentation (for Laravel 5.2 as stated in your question) documentation:
The values method returns a new collection with the keys reset to consecutive integers

spatie / laravel-translatable Fields Translating

I'm using spatie/laravel-translatable package for translating some fields in my model.
I have model model where declated that 'title' field is translatable attribute.
When I getting list of my Model data in controller controller this field is not translated and gives all possible translations in json format result1 (this package requires that translatable fields must be json type). But then I getting title from my model getting title its gives correct translated result correct result of title
I need to when I getting all data of my model every translatable fields was translated like :
{
"id": 6,
"title":"Tbilisi"
"country_id": 4
},
Please help if it possible to get data like this. thanks.

(Ember.js) How to save Sideloaded data from ajax call?

Good day!
Just want to ask on how to create a JSONAPISerializer for an ajax call?
From what I understand on the docs. I must first create a model before I can make a JSONAPISerializer. But I need to call a custom endpoint that is not listed as my model.
My goal is to pushPayload all the sideloaded data coming from my endpoint. but the problem is :
{
"data":[
{
"type":"promotions-verify", <----- it's not an actual model
"attributes":{
"cart-items-discount-in-cents":21900
},
"relationships":{...}, <---- sideloaded data that I want to push on ember-data
}],
"included": [] <---- sideloaded data that I want to push on ember-data
}
Is there a reason you can't make a model for promotions-verify? That would be the cleanest way to implement loading in the side-loaded data, since Ember would handle much of the serialization/pushing to the store for you.
If that isn't possible and you make an ajax request, you may need to map the relationships and included payloads to match up with one another (Lodash _.map() could work well for this). Then you can manually push that data (pushPayload) to the Ember store, while ensuring that the items you're pushing also have models and serializers.
Also, I'm not sure if this was accidental, but your example payload doesn't conform to JSON API standards – the relationships object should be nested within data. This will affect how Ember serializes the data, as it's expecting:
{
"data": [{
"id": 1,
"type": "promotions-verify",
"attributes": {},
"relationships": {}
}],
"included": []
}

Laravel: Remove an attribute in returned result

I have the following code:
$orders = Order::all();
return $orders;
This returns something like this:
[
{
"id": 123,
"qr_code": "foo.png",
"qr_code_url": "http://example.com/foo.png"
},
{
"id": 112,
"qr_code": "bar.png",
"qr_code_url": "http://example.com/var.png"
}
]
Note that qr_code_url is an appended attribute, and not an attribute stored in the database.
I want to return this collection back to the user without the attribute: qr_code, in this case. So like this:
[
{
"id": 123,
"qr_code_url": "http://example.com/foo.png"
},
{
"id": 112,
"qr_code_url": "http://example.com/var.png"
}
]
Looking at the collection functions, i can't seem to find an easy way to do this:
https://laravel.com/docs/5.4/collections
The only functions I have found close to what I want is: except and forget, but they seem to just work on a 1 dimension array. Not a collection result returned by a model.
How can I solve my problem?
You can set your attribute as hidden on the model class (see Hidding Attributes From Json)
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = ['qr_code'];
The attribute will still be loaded, but it won't be shown in your collections.
If you don't want to make it permanent, you can use the makeHidden() eloquent method as described on the docs:
Temporarily Modifying Attribute Visibility
If you would like to make some typically hidden attributes visible on
a given model instance, you may use the makeVisible method. The
makeVisible method returns the model instance for convenient method
chaining:
return $user->makeVisible('attribute')->toArray();
Likewise, if you
would like to make some typically visible attributes hidden on a given
model instance, you may use the makeHidden method.
return $user->makeHidden('attribute')->toArray();
You can use
$model->offsetUnset('propertyName');
$eloquentCollection->transform(function (Model $result) use ($forgetThisKey) {
$attributes = $result->getAttributes();
unset($attributes[$forgetThisKey]);
$result->setRawAttributes($attributes, true);
return $result;
});
When you build api the recommended way of controlling output data is to use fractal transformers.
If it's to much and you want to keep it simple you can use laravel pluck method on collections.
have had experience with this too. I've found a good solution here.
But, if you like a one-liner solution, you can also use the ff methods of Eloquent's Model class:
setHidden(array $hidden)
Ex: $user->setHidden(['name'])

Retrieve all OptionSet values using OData in Dynamics CRM

I am quite new to Dynamics CRM. I am building an app which should update entity in Dynamics CRM. I can update simple types without any issues. Now the situation is, I have declared some custom Option Sets in Contact entity.
Is there any way to retrieve all the possible OptionSet values (text and value) so that my app can look for appropriate value and set it in the payload it is generating?
I can not find any endpoint in WebAPI as well as XRMServices/2011/OrganizationData.svc. Any help would be really awesome.
You can use either the Web API or Organisation Service to retrieve The metadata and data models in Microsoft Dynamics CRM. Check out the sub articles of that one for specific examples and details.
Web API example Querying EntityMetadata attributes.
The following query will return only the PicklistAttributeMetadata
attributes and will include the LogicalName as well as expanding the
OptionSet and GlobalOptionSet collection-valued navigation properties.
GET [Organization URI]/api/data/v8.1/EntityDefinitions(70816501-edb9-4740-a16c-6a5efbc05d84)/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet,GlobalOptionSet
Another option would be to get the data via the StringMap entity:
[Organization URI]/api/data/v9.1/stringmaps?fetchXml=<fetch><entity name='stringmap'><filter><condition attribute='objecttypecodename' operator='in'><value>account</value><value>opportunity</value></condition></filter></entity></fetch>
Will provide data that looks like this:
{
"#odata.etag": "W/\"406742363\"",
"value": "Open",
"attributename": "statecode",
"langid": 1033,
"objecttypecode": "opportunity",
"attributevalue": 0,
"stringmapid": "0fe09734-3914-e711-80ef-e0071b6a7121",
"organizationid": "f95718b2-5c63-46df-adc3-c3b546cf686a",
"displayorder": 1
},
{
"#odata.etag": "W/\"406742364\"",
"value": "Won",
"attributename": "statecode",
"langid": 1033,
"objecttypecode": "opportunity",
"attributevalue": 1,
"stringmapid": "10e09734-3914-e711-80ef-e0071b6a7121",
"organizationid": "f95718b2-5c63-46df-adc3-c3b546cf686a",
"displayorder": 2
},
Simpler query:
[Organization URI]/api/data/v9.1/stringmaps?$filter=objecttypecode eq 'account' or objecttypecode eq 'opportunity'
If your options are global, this is the easiest way to get all options:
/api/data/v9.1/GlobalOptionSetDefinitions(Name='new_category')
Use below code to get specific option set for specific entity:
(replace EntityLogicalName and AttributeLogicalName with your input params)
GET [Organization URI]/api/data/v9.1/EntityDefinitions(LogicalName='EntityLogicalName')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options),GlobalOptionSet($select=Options)&$filter=LogicalName eq 'AttributeLogicalName'
First, you need the attribute name and type, which you can find here:
/api/data/v9.1/EntityDefinitions(LogicalName='myEntity')?$select=LogicalName&$expand=Attributes($select=LogicalName)
Replace myEntity above with your entity name. The resulting page lists all the attributes that make up your entity. Locate the desired option set attribute and note its logical name and type.
Armed with that information, go here:
/api/data/v9.1/EntityDefinitions(LogicalName='myEntity')/Attributes(LogicalName='myAttribute')/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options),GlobalOptionSet($select=Options)
Replace myEntity and myAttribute with your entity name and attribute name, respectively. If your attribute type is not MultiSelectPicklistAttributeMetadata, replace that with the correct type that was found on the previous page. This returns a list of all the possible values for the option set (both text and numeric values).

Resources