Laravel data recording with API - laravel

I save the received data from the API to the database. In my API result, there is the following answer:
"opponents": [
{
"opponent": {
"acronym": "RH",
"id": 127276,
"image_url": "/image/127276/reverse_heaven_logo_std.png",
"location": null,
"modified_at": "2020-04-14T19:03:48Z",
"name": "Reverse Heaven",
"slug": "reverse-heaven"
},
"type": "Team"
},
{
"opponent": {
"acronym": " neon",
"id": 2061,
"image_url": "/image/2061/neon_esport.png",
"location": "PH",
"modified_at": "2020-04-14T19:04:02Z",
"name": "Neon Esports",
"slug": "neon-esports"
},
"type": "Team"
}
],
If i use var_dump($opponents), i receive only last opponent from API. How can I save exactly 2 values that are in the array under the same name opponent->name?

Since you are using laravel, you may use collections.
$decoded = json_decode($opponents);
return collect($decoded->opponents)->pluck('opponent.name')->toArray();
you may do it in a single line if you prefer;
return collect(json_decode($opponents)->opponents)->pluck('opponent.name')->toArray();

first decode the json like this
$decoded_opponents = json_decode($opponents);
then create a empty array
$array = [];
run a foreach loop on you decoded data
foreach($decoded_opponents->opponents as $key=>$value){
$array[]=$value->opponent->name;
}
the names now stored in $array

Related

Delete existing Records if they are not in sent array Rails 5 API

I need help on how to delete records that exist in the DB but not in array sent in a request;
My Array:
[
{ "id": "509",
"name": "Motions move great",
"body": "",
"subtopics": [
{
"title": "Tywan",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
},
{
"title": "Transportations Gracious",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
},
{
"title": "Transportation part",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
}
]
},
{
"name": "Motions kkk",
"body": "",
"subtopics": [
{
"title": "Transportations",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
}
]
}
]
Below is my implementation: where am going wrong?
#topics = #course.topics.map{|m| m.id()}
#delete= #topics
puts #delete
if Topic.where.not('id IN(?)', #topics).any?
#topics.each do |topic|
topic.destroy
end
end
it's not clear to me where, in your code, you pick the ids sent in the array you showed before... so I'm assuming like this:
objects_sent = [
{ "id": "509",
"name": "Motions move great",
"body": "",
"subtopics": [
{
"title": "Tywan",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
},
{
"title": "Transportations Gracious",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
},
{
"title": "Transportation part",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
}
]
},
{
"name": "Motions kkk",
"body": "",
"subtopics": [
{
"title": "Transportations",
"url_path": "https://ugonline.s3.amazonaws.com/resources/6ca0fd64-8214-4788-8967-b650722ac97f/WhatsApp+Audio+2021-09-24+at+13.57.34.mpeg"
}
]
}
]
since you have your array like this, the only information you need to query on database is the ids (also, assuming the id's in the array are the id's on database, otherwise it wouldn't make sense). You can get them like this:
sent_ids = objects_sent.map{|o| o['id'].to_i}
Also, it seems to me that, for the code you showed, you want to destroy them based on a specific course. There would be 2 ways to do that. First, using the relationship (I prefer like this one):
#course.topics.where.not(id: sent_ids).destroy_all
Or you can do the query directly on the Topic model, but passing the course_id param:
Topic.where(course_id: #course.id).where.not(id: sent_ids).destroy_all
ActiveRecord is smart enough to mount that query correctly in both ways. Give it a test and see which works better for you

How to cleanly batch queries together in Gremlin

I am writing a GraphQL resolver that retrieves all vertices by a particular edge using the following query (created returns label person):
software {
created {
name
}
}
Which would resolve to the following Gremlin Query for each software node found:
g.V().hasLabel('software').has('name', 'ripple').in('created')
This returns a result that includes all properties of the object:
{
"result": [
{
"#type": "d",
"#rid": "#24:0",
"#version": 6,
"#class": "person",
"in_knows": [
"#35:0"
],
"name": "josh",
"out_created": [
"#32:0",
"#33:0"
],
"age": 32,
"#fieldTypes": "in_knows=g,out_created=g"
}
],
"dbStats": {
...
}
}
I realize that this will fall foul on GraphQL's N+1 query so i'm trying to batch queries together using a Dataloader pattern. (i'm also hoping to do property selections, so i'm not asking the database to return too much info)
So i'm trying to craft a query like so:
g.V().union(
__.hasLabel('software').has('name', 'ripple').
project('parent', 'child').by('id').
by(__.in('created').fold()),
__.hasLabel('software').has('name', 'lop').
project('parent', 'child').by('id').
by(__.in('created').fold())
)
But this results in the following where the props are missing and it just includes the id of the vertices I want:
{
"result": [
{
"parent": "ripple",
"child": [
"#24:0"
]
},
{
"parent": "lop",
"child": [
"#22:0",
"#23:0",
"#24:0"
]
}
],
"dbStats": {
...
}
}
My Question is, how can I have the Gremlin query return all of the props for the found vertices and none of the other props? Should I even been doing batching this way?
For anyone else reading, the query I was trying to write wouldn't work because the TraversalSet created in the .by(_.in('created') can't be cast from a List to an ElementMap as the stream cardinality wouldn't be enforced. (You can only have one record per row, I think?)
My working query would be to duplicate the keys for each row and specify the props needed (the query below is ok for gremlin 3.3 as used in ODB, otherwise if you've got < gremlin 3.4 replace the last by step with be(elementMap('name', 'age')):
g.V().union(
__.hasLabel('software').has('name', 'ripple').
as('parent').
in('created').as('child').
select('parent', 'child').
by(values('name')).
by(properties('id', 'name', 'age').
group().by(__.key()).
by(__.value())),
__.hasLabel('software').has('name', 'lop').
as('parent').
in('created').as('child').
select('parent', 'child').
by(values('name')).
by(properties('id', 'name', 'age').
group().by(__.key()).
by(__.value()))
)
So that you get a result like this:
{"data": [
{
"parent": "ripple",
"child": {
"id": 5717,
"name": "josh",
"age": 32
}
},
{
"parent": "lop",
"child": {
"id": 5709,
"name": "peter",
"age": 35
}
},
{
"parent": "lop",
"child": {
"id": 5713,
"name": "marko",
"age": 29
}
},
{
"parent": "lop",
"child": {
"id": 5717,
"name": "josh",
"age": 32
}
}
]
}
Which would allow you to create a lookup where you concat all results for "lop" and "ripple" into arrays.

Data from geoJSON API call in Larvel 5.8

I am trying to retrieve data from the weather.gov API - it returns the format in geoJSON and I am not sure how to actually get the data I want from it.
If I am using the weatherbit.io API, I have no issues as it returns JSON format in which I can pull from rather easily.
I am using GuzzleHTTP to make the API call.
I am playing around with learning APIs and I have an interest in weather so I figured I would work on an application in which I could pull information from the local weather station and output it in to readable format for users in a table.
The code I am currently using is:
$api_call = https://api.weather.xxx/points/LAT,LON;
$client = new \GuzzleHttp\Client();
$request = $client->get($api_call);
if ($request->getStatusCode() == 200) {
$weatherRequest = $request->getBody();
$requestedWeather = json_decode($weatherRequest);
$currentweather = $requestedWeather; ** THIS IS WHERE I NEED HELP ***
}
return $currentweather;
});
return view('currentweather', ["currentweather" => $currentweather]);
When I am returning $currentweather and var_dump it to the view, it gives me all the geoJSON data but I don't know how to correctly iterate through the data to pull the information I need.
When I pull from another API it gives a different JSON format which I can just pull like so:
$api_call = https://api.weatherbit.xx/v2.0/current?
$client = new \GuzzleHttp\Client();
$request = $client->get($api_call);
if ($request->getStatusCode() == 200) {
$weatherRequest = $request->getBody();
$requestedWeather = json_decode($weatherRequest);
$currentweather = $requestedWeather->data;
}
return $currentweather;
});
return view('currentweather', ["currentweather" => $currentweather]);
}
And when I use $currentweather in my view I can pull any data I need with the object string name. I am not sure how to pull the data when it's leading off with the #Context tag.
The data I want lies in the "properties" part of the geoJSON array and I just can't seem to figure out how to get that in the way I am currently using.
This is my geoJSON array return:
{ "#context": [ "https://raw.githubusercontent.xxx/geojson/geojson-ld/master/contexts/geojson-base.jsonld", { "wx": "https://api.weather.xxx/ontology#", "s": "https://schema.org/", "geo": "http://www.opengis.xxx/ont/geosparql#", "unit": "http://codes.wmo.xxx/common/unit/", "#vocab": "https://api.weather.xxx/ontology#", "geometry":
{ "#id": "s:GeoCoordinates", "#type": "geo:wktLiteral" }, "city": "s:addressLocality", "state": "s:addressRegion", "distance": { "#id": "s:Distance", "#type": "s:QuantitativeValue" }, "bearing": { "#type": "s:QuantitativeValue" }, "value": { "#id": "s:value" }, "unitCode":
{ "#id": "s:unitCode", "#type": "#id" }, "forecastOffice": { "#type": "#id" }, "forecastGridData": { "#type": "#id" }, "publicZone": { "#type": "#id" }, "county": { "#type": "#id" } } ], "id": "https://api.weather.xxx/points/xxx,xxx", "type": "Feature", "geometry": { "type": "Point", "coordinates": [ xxx, xxx ] }, "properties":
{ "#id": "https://api.weather.xxx/points/xxx,xxx", "#type": "wx:Point", "cwa": "xxx", "forecastOffice": "https://api.weather.xxx/offices/xxx", "gridX": 86, "gridY": 77, "forecast": "https://api.weather.xxx/gridpoints/xxx/xx,xx/forecast", "forecastHourly": "https://api.weather.xxx/gridpoints/xxx/xx,xx/forecast/hourly", "forecastGridData": "https://api.weather.xxx/gridpoints/xxx/xx,xx", "observationStations": "https://api.weather.xxx/gridpoints/xxx/xx,xx/stations", "relativeLocation":
{ "type": "Feature", "geometry": { "type": "Point", "coordinates": [ xxx, xxx ] }, "properties": { "city": "xxx", "state": "xx", "distance": { "value": xxxx.xxxxxxxxx, "unitCode": "unit:m" }, "bearing": { "value": 150, "unitCode": "unit:degrees_true" } } }, "forecastZone": "https://api.weather.xxx/zones/forecast/xxxxxx", "county": "https://api.weather.xxx/zones/county/xxxxxx", "fireWeatherZone": "https://api.weather.xxx/zones/fire/SCZ050", "timeZone": "America/New_York", "radarStation": "xxxx" } }
Thanks for your help!
Any member of the JSON object can be accessed via the same name on the object returned by json_decode. Your weatherbit example $requestedWeather->data works because everything is in a member called data. So... $requestedWeather->properties will get you what you want from the weather.gov API.
You can also pass true as a second argument to json_decode to get back a plain PHP array instead.
$requestedWeather = json_decode($weatherRequest, true);
var_dump($requestedWeather['properties']);
This is often recommended because JSON allows member names that are not valid PHP object property names (e.g., names containing hyphens).

Filter where attribute is in supplied array

Suppose I have these documents in a Things table:
{
"name": "Cali",
"state": "CA"
},
{
"name": "Vega",
"state": "NV",
},
{
"name": "Wash",
"state": "WA"
}
My UI is a state-picker where the user can select multiple states. I want to display the appropriate results. The SQL equivalent would be:
SELECT * FROM Things WHERE state IN ('CA', 'WA')
I have tried:
r.db('test').table('Things').filter(r.expr(['CA', 'WA']).contains(r('state')))
but that doesn't return anything and I don't understand why that wouldn't have worked.
This works for getting a single state:
r.db('test').table('Things').filter(r.row('state').eq('CA'))
r.db('test').table('Things').filter(r.expr(['CA', 'WA']).contains(r.row('state')))
seems to be working in some versions and returns
[
{
"id": "b20cdcab-35ab-464b-b10b-b2f644df73e6" ,
"name": "Cali" ,
"state": "CA"
} ,
{
"id": "506a4d1f-3752-409a-8a93-83385eb0a81b" ,
"name": "Wash" ,
"state": "WA"
}
]
Anyway, you can use a function instead of r.row:
r.db('test').table('Things').filter(function(row) {
return r.expr(['CA', 'WA']).contains(row('state'))
})

Group array items with eloquent

I have the following eloquent query:
$extras = EventExtra::select('id', 'category', 'name', 'price', 'description', 'company')->get();
It gets some data from me from my database. What i want is for the returned data to be grouped twice, first by the category and then second by the company so that in the end i have something like this returned to the client:
[
{
"name": "donation",
"collection": [
{
"name": "sampleCompany1",
"array": [
{
"name": "extra1",
"description": "",
"value": ""
},
{
"name": "extra4",
"description": "",
"value": ""
},
{
"name": "extra6",
"description": "",
"value": ""
}
]
}
]
},
{
"name": "donation",
"collection": [
{
"name": "sampleCompany2",
"array": [
{
"name": "extra2",
"description": "",
"value": ""
},
{
"name": "extra3",
"description": "",
"value": ""
}
]
}
]
}]
I just typed the above myself so it might not be valid object array but basically it shows what i want to accomplish here.
You can use Collection to build your custom object. Something like this:
$return_data = Collect();
To add items in the collection with a property, you can use the put function.
$inner_data->put('name',$extras->name);
You can also add a collection within a collection.
To just push an existing collection in the collection, use push function
$inner_data->push($some_collection)
EDIT: Since you want a working example, see this below:
Lets say you want to create the following using collection:
{
"name": "extra1"
"description": "",
"value": ""
}
You will do something like this:
$my_collection = Collect();
$my_collection->put('name','extra1');
$my_collection->put('description','');
$my_collection->put('value','');
Now you can add this collection to another collection where you don't need a key. So lets say now it looks like this:
[
{
"name": "extra1"
"description": "",
"value": ""
},
{
"name": "extra4"
"description": "",
"value": ""
}
]
You will now do:
$my_final_collection = Collect();
foreach($my_collections as $my_collection) {
$my_final_collection->push($my_collection); // and so on in a loop
}

Resources