Delete unwanted data from api result - php

I have a project in laravel which has API. I'm asking the API for posts(I call them recommendation).
Now my api response look like this -
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"id": 3,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
}
...
...
...
All is good but I don't wanna likes_count to be in the result. It is a relation method. I get from it all I need. It is if the user liked this post. And it is is_liked in the result . but likes_count automatically added to the response .
if($item->likesCount->contains($user->id)){
$item['is_liked']='true';
}
I tried delete it with
foreach ($recommendations as $item) {
unset($item['likes_count']);
}
But it doesn't do it.

I think the problem is how you are referencing the object data structure. You are attempting to unset() something that doesn't exist so no error is thrown but the likes_count isn't getting removed either.
Here's your code example (fixed and modified for demonstration):
<?php
$apiResult = <<<eod
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"id": 3,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres",
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
},
{
"id": 4,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres",
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
}
]
}
}
eod;
$result = json_decode($apiResult);
$data = $result->data->data;
var_dump($data);
// This should remove the likes_count array from the $result structure.
foreach ($data as &$item) {
unset($item->likes_count);
}
var_dump($data);

A quick way would be to make that 'attribute' (relation) hidden:
$recommendations->makeHidden('likes_count');
Though I am not sure how you are building your response.

Related

Getting Duplicate Data on Response On Laravel Eloquent

I am new in laravel in php. So it might be very silly mistake. I have song table and song categories table. I am trying to fetch all category with their respective songs. I have implemented larvel eloquent one to many relationship between song category and song.
Here is my code of fetching data:
public function getSongCategoriesWithSongs(){
$json_array = array();
$song_categories = SongCategory::all();
foreach ($song_categories as $item) {
# code...
$json = [];
$json['category'] = $item;
$json['songs'] = $item->songs;
array_push($json_array,$json);
}
return $json_array;
}
Here is response:
[{
"category": {
"id": 1,
"title": "Rock",
"created_at": "2020-12-20T02:58:32.000000Z",
"updated_at": "2020-12-20T02:58:32.000000Z",
"songs": [{
"id": 1,
"title": "Mere Mehboob",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/2u039f-a.akamaihd.net\/downloads\/ringtones\/files\/mp3\/mere-mehboob-qayamat-hogi-52150.mp3",
"created_at": "2020-12-20T13:26:30.000000Z",
"updated_at": "2020-12-20T13:26:30.000000Z"
}, {
"id": 2,
"title": " Taaron Ke Shehar",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/newmp3ringtones.net\/assets\/sass\/Ringtones\/TaaronKeSheharRingtoneByNehaKakkarJubinNautiyal2145436126.mp3",
"created_at": null,
"updated_at": null
}, {
"id": 3,
"title": "Bewafa Tera Masoom Chehra",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/newmp3ringtones.net\/assets\/sass\/Ringtones\/BewafaTeraMasoomChehraRingtoneByJubinNautiyal352778308.mp3",
"created_at": null,
"updated_at": null
}]
}
}, {
"songs": [{
"id": 1,
"title": "Mere Mehboob",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/2u039f-a.akamaihd.net\/downloads\/ringtones\/files\/mp3\/mere-mehboob-qayamat-hogi-52150.mp3",
"created_at": "2020-12-20T13:26:30.000000Z",
"updated_at": "2020-12-20T13:26:30.000000Z"
}, {
"id": 2,
"title": " Taaron Ke Shehar",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/newmp3ringtones.net\/assets\/sass\/Ringtones\/TaaronKeSheharRingtoneByNehaKakkarJubinNautiyal2145436126.mp3",
"created_at": null,
"updated_at": null
}, {
"id": 3,
"title": "Bewafa Tera Masoom Chehra",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/newmp3ringtones.net\/assets\/sass\/Ringtones\/BewafaTeraMasoomChehraRingtoneByJubinNautiyal352778308.mp3",
"created_at": null,
"updated_at": null
}]
}, {
"category": {
"id": 2,
"title": "Soft",
"created_at": null,
"updated_at": null,
"songs": []
}
}, {
"songs": []
}]
As you can see songs get repeated.
UPDATE
Solved using eager loading
public function getSongCategoriesWithSongs(){
return SongCategory::with('songs')->get();
}
But don't know why the foreach method not working.
Try this code
public function getSongCategoriesWithSongs(){
$json_array = array();
$song_categories = SongCategory::all();
foreach ($song_categories as $item) {
$json_array[] = ['category' => $item, 'songs' => $item->songs] ;
}
return $json_array;
}
The problem is that you assign the same relation twice.
Each SongCategory already has a collection of songs inside.
So in your foreach block, you assign a category with $json['category'] => $item which will load all related songs and pass them to the final JSON object. And you duplicate this by passing the next item $json['songs'] = $item->songs to the same array. Default Laravel behavior will be to fetch all related objects and transform them into JSON.
I would suggest you to use Laravel resources to return JSON objects with exact shapes: API Resources.
You can fix your code block without eager loading by removing $json['songs'] = $item->songs assignment.
Eager loading works because you passed all your objects only once.

how should i decode the correct json response?

I am using Laravel 5.7 to build an API that provides a JSON response. I am creating the following JSON but it needs some changes. Table contain booking_pics columns in which multiple images stored using , separated. I want fetch in json as object in array. i am display json but only last image is display others is not, need solution.
Controller:
$get_booking_details= DB::table('table_booking_list')
->join('table_booking_details', 'table_booking_list.booking_id', '=', 'table_booking_details.booking_id')
->select('table_booking_details.*')
->where('table_booking_details.booking_id',$booking_id)
->get();
foreach($get_booking_details as $item)
{
foreach(explode(",",$item->booking_pics) as $items)
{
$item->booking_pics=[["image" => $items]];
}
}
return response()->json(['success' => '1','data' =>$get_booking_details]);
json response:
{
"success": "1",
"data": [
{
"id": 1,
"booking_list_id": 1,
"booking_id": 1,
"booking_name": "hockey stadium",
"booking_area": "kolhapur",
"booking_status": 0,
"time": "6.00 am to 8.00pm",
"booking_pics": [
{
"image": "http://192.168.1.132:8000/images/ground_pic/2.jpg"
}
],
"available_sports": "hockey,cricket",
"booking_amenities": "parking,toilet,water",
"booking_rating": 4.5,
"booking_area_address": "MSEB Ring Road, Datta Colony, Kolhapur, Maharashtra, 416008",
"longitude": "85.501980",
"latitude": "23.624420",
"updated_at": "2019-06-26 16:42:02",
"created_at": "0000-00-00 00:00:00"
}
]
}
Required json:
{
"success": "1",
"data": [{
"id": 1,
"booking_list_id": 1,
"booking_id": 1,
"booking_name": "hockey stadium",
"booking_area": "kolhapur",
"booking_status": 0,
"time": "6.00 am to 8.00pm",
"booking_pics": [{
"image": "http://192.168.1.132:8000/images/ground_pic/1.jpg"
},
{
"image": "http://192.168.1.132:8000/images/ground_pic/2.jpg"
}
],
"available_sports": "hockey,cricket",
"booking_amenities": "parking,toilet,water",
"booking_rating": 4.5,
"booking_area_address": "MSEB Ring Road, Datta Colony, Kolhapur, Maharashtra, 416008",
"longitude": "85.501980",
"latitude": "23.624420",
"updated_at": "2019-06-26 16:42:02",
"created_at": "0000-00-00 00:00:00"
}]
}
Do it this way
foreach($get_booking_details as $item)
{
foreach(explode(",",$item->booking_pics) as $items)
{
$item->booking_pics["image"][] = $items;
}
}
fastest way would be creating a model and casting the data from database as a json
in model
protected $casts = [
'booking_pics' => 'json',
];

PHP - Retrieve JSON data and values [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I'm new into PHP and JSON and I have a problem, I want to retrieve a item and value from a JSON:
{
"status": true,
"webhook_type": 100,
"data": {
"product": {
"id": "lSEADIQ",
"attachment_id": null,
"title": "Registration",
"description": null,
"image": null,
"unlisted": false,
"type": "service",
"price": 1,
"currency": "EUR",
"email": {
"enabled": false
},
"stock_warning": 0,
"quantity": {
"min": 1,
"max": 1
},
"confirmations": 1,
"custom_fields": [
{
"name": "Forum username",
"type": "text",
"required": true
}
],
"gateways": [
"Bitcoin"
],
"webhook_urls": [],
"dynamic_url": "",
"position": null,
"created_at": "2018-10-01 12:51:12",
"updated_at": "2018-10-01 12:55:46",
"stock": 9223372036854776000,
"accounts": []
},
"order": {
"id": "8e23b496-121a-4dc6-8ec4-c45835680db2",
"created_at": "Tue, 02 Oct 2018 00:54:56 +0200",
"paid_at": null,
"transaction_id": null,
"confirmations": 1,
"required_confirmations": 3,
"received_amount": 0,
"crypto_address": "1NeNQws7JLbTr6bjekfeaXSV7XiyRsv7V8",
"crypto_amount": "0.4815",
"quantity": 1,
"price": 19.99,
"currency": "EUR",
"exchange_rate": "1.21",
"gateway": "BTC",
"email": "webhook#site.gg",
"ip_address": "123.456.789.111",
"agent": {
"geo": {
"ip": "214.44.18.6",
"iso_code": "US",
"country": "United States"
},
"data": {
"is_mobile": false,
"is_table": false,
"is_desktop": true,
"browser": {
"name": "Chrome",
"version": "63.0.3239.132"
}
}
},
"custom_fields": [
{
"name": "user_id",
"value": 184191
}
],
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3)"
}
}
}
I want to retrieve items from data -> order, for example "id" or "ip_address".
Thank you for read this, I hope someone can help me in this, because I'm lost, I started to code very recently and I'm trying to learn a lot.
Regards!
Where test.json is the json you uploaded, place it in a file named test.json and ensure its placed in the same directory.
<?php
$load = file_get_contents("test.json") or die("JSON load failed");
$json_a = json_decode($load, true);
print $json_a['data']['order']['ip_address'] . "\n";
?>
Gives:
123.456.789.111
My answer reads the JSON from a file as were it dumped directly in your code, which indeed it could be, it would make the code less readable and your file more messy.
If you dont want to place the file in the same directory, simply specify the full file path. E.g. file_get_contents("this/dir/here/test.json");
You can read about how json_decode works here, its essential we pass it the true parameter to make our arrays associative.
You can extract your need array from JSON data. You can use a loop too to read all your data inside the order array.
$array = json_decode($json, true);
$verbose = $array['data'];
$orderArray = $verbose['order'];
print_r($orderArray);
echo $orderArray['id'];
echo $orderArray['ip_address'];

PHP Array Conversion with removing Array Name

Hello i want to remove "news_list" from php json array.
{
"news_list": [
{
"id": 2,
"group_id": 1,
"news_title": "fbb",
"news_description": "gfhgfh",
"status": "Y",
"created_at": "2017-05-11 16:04:26",
"updated_at": "2017-05-11 16:04:26"
},
{
"id": 3,
"group_id": 1,
"news_title": "ewrdf",
"news_description": "dsfsdfdsfsdffffffffffffff",
"status": "Y",
"created_at": "2017-05-12 10:59:01",
"updated_at": "2017-05-12 10:59:01"
}
]
}
Desired Output :
[
{
"id": 2,
"group_id": 1,
"news_title": "fbb",
"news_description": "gfhgfh",
"status": "Y",
"created_at": "2017-05-11 16:04:26",
"updated_at": "2017-05-11 16:04:26"
},
{
"id": 3,
"group_id": 1,
"news_title": "ewrdf",
"news_description": "dsfsdfdsfsdffffffffffffff",
"status": "Y",
"created_at": "2017-05-12 10:59:01",
"updated_at": "2017-05-12 10:59:01"
}
]
is there ant in-built PHP function for same ?.if there i s any in built function then please convey me.
There is nothing like direct function to fetch any key data of json. You need to convert your json to array or object using json_decode and then can perform or fetch what you looking for.
$res = json_decode($data); // return object
print_r($res->news_list);
Or
$res = json_decode($data, true); // return array
print_r($res['news_list']);
Try this...
$oldDataArray = json_decode('{"news_list":[{"id":2,"group_id":1,"news_title":"fbb","news_description":"gfhgfh","status":"Y","created_at":"2017-05-11 16:04:26","updated_at":"2017-05-11 16:04:26"},{"id":3,"group_id":1,"news_title":"ewrdf","news_description":"dsfsdfdsfsdffffffffffffff","status":"Y","created_at":"2017-05-12 10:59:01","updated_at":"2017-05-12 10:59:01"}]}');
$newDataArray = $oldDataArray->news_list;
echo '<pre>';
print_r($newDataArray);
echo '</pre>';

Easiest way of accessing deep-nested value in json response?

I have the following response (I cut the extra short):
{
"meta": {
"current_page": "1",
"last_page": "1",
"per_page": "15",
"total": "1",
"from": "1",
"to": "1"
},
"Products": [
{
"archived": "0",
"committed_stock": "0",
"created_at": "2015-05-10T17:39:53+00:00",
"deleted": "0",
"description": "desc",
"id": "43061710",
"links": {
"Users": [
{
"id": "107534",
"type": "created_by"
}
],
"Attributes": [
{
"id": "31538870"
}
]
}
}
]
}
Everytime I get this response, there will only be one item in "Attributes." What is the easiest way of grabbing this value? So far I have this:
$json = json_decode($json_data);
$json = json_decode($json_data, true);
echo $json["Products"][0]["links"]["Attributes"][0]["id"];
try this:
var_dump( $json->Products[0]->links->Attributes);
the object field could be ether also an object, or an array:
refer to field: $object->object
refer to array's i cell: $object->array[i]
P.S.
please edit the json, it's missing it's end...
You may also want to try some JSON Path libs for PHP: https://github.com/Peekmo/JsonPath

Categories