How to extract messages string from JSON - ruby

I am attempting to reference the message array contained within this JSON but cant seem to get it.
[
{
"MessageThreadID": 1,
"CustomerID": 171,
"MessageType": 1,
"Subject": "Test Message",
"OpenDate": "2015-09-17T00:00:00",
"Closed": false,
"ClosedDate": null,
"Messages": [
{
"IBMessageID": 1,
"MessageThreadID": 1,
"MessageText": "Test Message",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-17T17:23:00"
},
{
"IBMessageID": 2,
"MessageThreadID": 1,
"MessageText": "Test this Update",
"FromCustomer": false,
"UserID": 1,
"Date": "2015-09-17T17:23:00"
},
{
"IBMessageID": 3,
"MessageThreadID": 1,
"MessageText": "My New Message",
"FromCustomer": false,
"UserID": 1,
"Date": "2015-09-17T17:23:00"
},
{
"IBMessageID": 4,
"MessageThreadID": 1,
"MessageText": "Reply",
"FromCustomer": false,
"UserID": 1,
"Date": "2015-09-17T17:05:00"
},
{
"IBMessageID": 5,
"MessageThreadID": 1,
"MessageText": "Some sensible shit",
"FromCustomer": false,
"UserID": 1,
"Date": "2015-09-17T17:23:00"
},
{
"IBMessageID": 14,
"MessageThreadID": 1,
"MessageText": "Message 2",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-21T14:10:00"
},
{
"IBMessageID": 16,
"MessageThreadID": 1,
"MessageText": "Message 2",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-22T16:22:00"
},
{
"IBMessageID": 25,
"MessageThreadID": 1,
"MessageText": "Added via abacus\r\n",
"FromCustomer": false,
"UserID": 1,
"Date": "2015-09-22T16:22:00"
},
{
"IBMessageID": 26,
"MessageThreadID": 1,
"MessageText": "sdsdsdsd",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-22T16:40:00"
},
{
"IBMessageID": 27,
"MessageThreadID": 1,
"MessageText": "test",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-22T17:02:00"
},
{
"IBMessageID": 28,
"MessageThreadID": 1,
"MessageText": "test",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-22T17:06:00"
}
]
}
]
The furthest I have gotten is:
#cleanmessages = JSON.parse([#messages].to_json).first
This returns:
[
{
"IBMessageID" =>1,
"MessageThreadID" =>1,
"MessageText" =>"Test Message",
"FromCustomer" =>true,
"UserID" =>nil,
"Date" =>"2015-09-17T17:23:00 "},
{
"IBMessageID"=>2,
"MessageThreadID" =>1,
"MessageText" =>"Test this Update",
"FromCustomer" =>false,
"UserID" =>1,
"Date" =>"2015-09-17T17:23:00 "},
{
"IBMessageID"=>3,
"MessageThreadID" =>1,
"MessageText" =>"My New Message",
"FromCustomer" =>false,
"UserID" =>1,
"Date" =>"2015-09-17T17:23:00 "},
{
"IBMessageID"=>4,
"MessageThreadID" =>1,
"MessageText" =>"Reply",
"FromCustomer" =>false,
"UserID" =>1,
"Date" =>"2015-09-17T17:05:00 "},
{
"IBMessageID"=>5,
"MessageThreadID" =>1,
"MessageText" =>"Some sensible shit",
"FromCustomer" =>false,
"UserID" =>1,
"Date" =>"2015-09-17T17:23:00 "},
{
"IBMessageID"=>14,
"MessageThreadID" =>1,
"MessageText" =>"Message 2",
"FromCustomer" =>true,
"UserID" =>nil,
"Date" =>"2015-09-21T14:10:00 "},
{
"IBMessageID"=>16,
"MessageThreadID" =>1,
"MessageText" =>"Message 2",
"FromCustomer" =>true,
"UserID" =>nil,
"Date" =>"2015-09-22T16:22:00 "},
{
"IBMessageID"=>25,
"MessageThreadID" =>1,
"MessageText" =>"Added via abacus\r\n",
"FromCustomer" =>false,
"UserID" =>1,
"Date" =>"2015-09-22T16:22:00 "},
{
"IBMessageID"=>26,
"MessageThreadID" =>1,
"MessageText" =>"sdsdsdsd",
"FromCustomer" =>true,
"UserID" =>nil,
"Date" =>"2015-09-22T16:40:00 "},
{
"IBMessageID"=>27,
"MessageThreadID" =>1,
"MessageText" =>"test",
"FromCustomer" =>true,
"UserID" =>nil,
"Date" =>"2015-09-22T17:02:00 "},
{
"IBMessageID"=>28,
"MessageThreadID" =>1,
"MessageText" =>"test",
"FromCustomer" =>true,
"UserID" =>nil,
"Date" =>"2015-09-22T17:06:00
}
]
How do i reference each element within each array. I want to in the end be able to display each element sepearately for each thread.

This will give you a hash with the message grouped by the MessageThreadID
#cleanmessages.group_by{ |msg_hash| msg_hash['MessageThreadID']}

Not clear what output you actually want.
document = JSON.parse([#messages].to_json)
document.each do |thread|
# gives you all text messages within the current thread: "Test Message", "Test this Update", ...
messages = thread['Messages'].map {|m| m['MessageText']}
# iterates over all messages in the current thread
thread['Messages'].each {|m| puts "Message #{m['IBMessageID']} from thread #{thread['MessageThreadID']}"}
end
In general JSON.parse doesn't return something special. It returns either Array for corresponding JSON array or Hash for corresponding JSON object.

Related

Laravel add new properties to returned API resource object does not work

I have below Laravel controller methods, I need to customize the returned result, but I have problem as below:
public function getCart(CartProductsRequest $request)
{
try {
$carts = json_decode($request->cart);
$products = [];
$total = 0;
$allCurrency = "";
foreach ($carts as $key => $cart) {
$product = new ProductResource(Product::findOrFail($cart->productId));
$total += $product->finalPrice * $cart->quantity;
$product->qty = $cart->quantity;
$product->inStock = $product->inStock();
$product->totalPrice = $cart->quantity * $product->finalPrice;
$products[] = $product;
$allCurrency = $product->currency->symbol;
}
$cart = ['products' => $products, 'total' => round($total, 2), 'currency' => $allCurrency];
return JsonResponse::respondSuccess(trans(JsonResponse::MSG_SUCCESS), $cart);
} catch (\Exception $e) {
return JsonResponse::respondError($e->getMessage());
}
}
The result (products) does not contain the new added probertites like qty
, I don't know way,
The API resource is (the fields returned):
public function toArray($request)
{
return [
'id' => $this->id,
'name_en' => $this->name_en,
'name_ar' => $this->name_ar,
'slug' => $this->slug,
'details' => $this->details,
'currency' => $this->currency,
'offer' => $this->offer->first(),
'brand' => $this->brand,
'category' => $this->category,
'specifications' => SpesificationResource::collection($this->specifications),
'merchant' => $this->merchant,
'images' => count($this->images) > 0 ? ImageResource::collection($this->images) : asset("/images/default.png"),
"price" => $this->price,
"finalPrice" => $this->offer->first() ? $this->price - ($this->price * $this->offer->first()->discount / 100) : $this->price,
'quantity' => $this->quantity,
'inStock' => $this->inStock(),
'status' => $this->status,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
The result is :
{
"result": "success",
"content": {
"products": [
{
"id": 1,
"nameEn": "Device 1",
"nameAr": "\u062c\u0647\u0627\u0632 1",
"slug": "device-1",
"details": "Veniam quis accusamus est ea ad ipsa hic. Distinctio assumenda quibusdam magnam nobis aut aliquam nesciunt. Quia unde sapiente maiores temporibus rerum eum. Porro debitis est error quia.",
"currency": {
"id": 92,
"nameAr": "\u0627\u0644\u0644\u064a\u0631\u0629 \u0627\u0644\u062a\u0631\u0643\u064a\u0629",
"nameEn": "Turkish Lira",
"code": "TRY",
"symbol": "TL",
"image": null,
"status": 1,
"isDefault": 1,
"createdAt": null,
"updatedAt": null
},
"offer": {
"id": 1,
"nameAr": "offer 1",
"nameEn": "offer 1",
"details": null,
"image": null,
"status": 1,
"discount": "20.00",
"addedBy": 1,
"updatedBy": null,
"startDate": "2021-08-05 08:29:35",
"endDate": null,
"createdAt": "2021-08-05T08:29:35.000000Z",
"updatedAt": "2021-08-05T08:29:35.000000Z",
"pivot": {
"productId": 1,
"offerId": 1
}
},
"brand": {
"id": 7,
"nameAr": "Kasandra Volkman",
"nameEn": "Nathanial Larson",
"photo": null,
"createdAt": "2021-08-05T08:21:34.000000Z",
"updatedAt": "2021-08-05T08:29:34.000000Z"
},
"category": {
"id": 6,
"nameAr": "Miss Verna Breitenberg V",
"nameEn": "Laurel Wehner IV",
"details": "Dolor debitis itaque maiores sed nihil magnam. Illo molestiae quas sed nihil possimus ut. Non qui enim possimus officia quaerat quod voluptate.",
"image": "111628152906.jpg",
"status": 1,
"slug": "laurel-wehner-iv",
"lft": 0,
"rgt": 0,
"parentId": null
},
"specifications": [
{
"id": 1,
"nameEn": "Vance Miller",
"nameAr": "Dr. Wellington Jones",
"value": "test",
"image": null,
"createdAt": "2021-08-05T07:53:35.000000Z",
"updatedAt": "2021-08-05T08:29:35.000000Z"
}
],
"merchant": {
"id": 2,
"name": "merchant",
"email": "merchant#merchants.com",
"phone": "1111",
"firstName": "merchant",
"lastName": "merchant",
"cityId": 1,
"street": null,
"buildNumber": null,
"houseNumber": null,
"status": 1,
"emailVerifiedAt": "2021-08-05T08:29:34.000000Z",
"roleId": 2,
"profilePhotoPath": null,
"createdBy": null,
"updatedBy": null,
"currencyId": null,
"createdAt": "2021-08-05T08:29:34.000000Z",
"updatedAt": "2021-08-05T08:29:34.000000Z",
"deletedAt": null,
"profilePhotoUrl": "https:\/\/ui-avatars.com\/api\/?name=merchant&color=7F9CF5&background=EBF4FF"
},
"images": [
{
"id": 12,
"name": "\/images\/products\/1_1.png",
"orderingShow": 1,
"createdAt": "2021-08-05T08:39:10.000000Z",
"updatedAt": "2021-08-05T08:39:10.000000Z"
},
{
"id": 13,
"name": "\/images\/products\/1_2.png",
"orderingShow": 2,
"createdAt": "2021-08-05T08:39:10.000000Z",
"updatedAt": "2021-08-05T08:39:10.000000Z"
},
{
"id": 14,
"name": "\/images\/products\/1_3.png",
"orderingShow": 3,
"createdAt": "2021-08-05T08:39:10.000000Z",
"updatedAt": "2021-08-05T08:39:10.000000Z"
},
{
"id": 15,
"name": "\/images\/products\/1_4.png",
"orderingShow": 4,
"createdAt": "2021-08-05T08:39:10.000000Z",
"updatedAt": "2021-08-05T08:39:10.000000Z"
},
{
"id": 16,
"name": "\/images\/products\/1_5.png",
"orderingShow": 5,
"createdAt": "2021-08-05T08:39:10.000000Z",
"updatedAt": "2021-08-05T08:39:10.000000Z"
},
{
"id": 17,
"name": "\/images\/products\/1_6.png",
"orderingShow": 6,
"createdAt": "2021-08-05T08:39:10.000000Z",
"updatedAt": "2021-08-05T08:39:10.000000Z"
},
{
"id": 18,
"name": "\/images\/products\/1_7.png",
"orderingShow": 7,
"createdAt": "2021-08-05T08:39:10.000000Z",
"updatedAt": "2021-08-05T08:39:10.000000Z"
},
{
"id": 19,
"name": "\/images\/products\/1_8.png",
"orderingShow": 8,
"createdAt": "2021-08-05T08:39:10.000000Z",
"updatedAt": "2021-08-05T08:39:10.000000Z"
}
],
"price": "100.00",
"finalPrice": 80,
"quantity": 20,
"inStock": true,
"status": 1,
"createdAt": "2021-08-05T08:21:35.000000Z",
"updatedAt": "2021-08-05T08:42:43.000000Z"
}
],
"total": 0,
"currency": "TL"
},
"message": "responses.msg_success",
"status": 200
}
Can you help me please to determine the problem?? (I need the qty in the result) Or if there is another way to map the result

Laravel apply sortBy to a related models collection

I am using the below code:
$greatDeals = $greatDealsinitial->sortBy(function ($deal, $key) {
return $deal->hotel->room[0]->price;
});
Here room is an array, I want to sort this collection by price in the room array.
But I can't use return $row->hotel->room->price;
So how can I sort this?
my collection :
[
{
"id": 2,
"hotel_id": 1,
"deal_code": "sfg",
"date": "2018-04-13 00:00:00",
"discount": 12,
"status": 1,
"created_at": "2018-04-13 11:21:18",
"updated_at": "2018-04-13 11:21:18",
"deleted_at": null,
"client_id": 1,
"hotel": {
"id": 1,
"name": "Aloft Dongguan Songshan Lake",
"address": "Dongguan, China, 511700",
"phone": "76982106666",
"country": "101",
"country_name": "India",
"state": "35",
"state_name": "Tamil Nadu",
"city": "3551",
"city_name": "Abiramam",
"area": null,
"pincode": "511700",
"nearest_airport": null,
"nearest_railway": null,
"star": null,
"check_in": null,
"check_out": null,
"lat": "22.929869",
"lng": "113.89232800000002",
"description": null,
"astatus": "1",
"status": "0",
"created_at": "2018-04-13 10:27:30",
"updated_at": "2018-04-13 10:27:48",
"client_id": 1,
"hotel_age": null,
"hotel_privilege": "asdf",
"departure": "sdaf",
"checkout_fee": "asdf",
"book_policy": "sadf",
"hotel_secured": null,
"hotel_pets": null,
"hotel_other": null,
"room": [
{
"id": 3,
"roomtype_id": 2,
"room_count": null,
"max_adult": 2,
"max_children": 1,
"capacity": 3,
"room_number": null,
"floor": null,
"number": null,
"name": null,
"city_name": "Abiramam",
"city": 3551,
"price": "200.00",
"extra_bed_price": null,
"astatus": "1",
"status": "0",
"created_at": "2018-04-13 12:37:11",
"updated_at": "2018-04-13 12:37:52",
"deleted_at": null,
"client_id": 1,
"hotel_id": 1
},
{
"id": 1,
"roomtype_id": 1,
"room_count": null,
"max_adult": 2,
"max_children": 1,
"capacity": 3,
"room_number": null,
"floor": null,
"number": null,
"name": null,
"city_name": "Abiramam",
"city": 3551,
"price": "435.00",
"extra_bed_price": null,
"astatus": "1",
"status": "0",
"created_at": "2018-04-13 10:33:24",
"updated_at": "2018-04-13 11:21:38",
"deleted_at": null,
"client_id": 1,
"hotel_id": 1
}
]
}
},
{
"id": 4,
"hotel_id": 2,
"deal_code": "ertgerf",
"date": "2018-04-13 00:00:00",
"discount": 1,
"status": 1,
"created_at": "2018-04-13 11:47:39",
"updated_at": "2018-04-13 11:53:45",
"deleted_at": null,
"client_id": 2,
"hotel": {
"id": 2,
"name": "Temperance Lane",
"address": "Temperance Ln, Sydney NSW 2000, Australia",
"phone": "9842814927",
"country": "14",
"country_name": "Austria",
"state": "281",
"state_name": "Carinthia",
"city": "6843",
"city_name": "Maria Rain",
"area": "test",
"pincode": "2000",
"nearest_airport": "demo",
"nearest_railway": "test",
"star": null,
"check_in": "09:30 AM",
"check_out": "04:30 PM",
"lat": "-33.86963590000001",
"lng": "151.20667979999996",
"description": "test description",
"astatus": "1",
"status": "0",
"created_at": "2018-04-13 10:43:16",
"updated_at": "2018-04-13 11:41:25",
"client_id": 2,
"hotel_age": null,
"hotel_privilege": "testtesttesttesttesttesttesttesttesttesttest",
"departure": "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest",
"checkout_fee": "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest",
"book_policy": "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest",
"hotel_secured": null,
"hotel_pets": null,
"hotel_other": "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest",
"room": [
{
"id": 2,
"roomtype_id": 1,
"room_count": null,
"max_adult": 2,
"max_children": 3,
"capacity": 5,
"room_number": null,
"floor": null,
"number": null,
"name": null,
"city_name": "Maria Rain",
"city": 6843,
"price": "345.00",
"extra_bed_price": null,
"astatus": "1",
"status": "0",
"created_at": "2018-04-13 10:46:04",
"updated_at": "2018-04-13 10:47:05",
"deleted_at": null,
"client_id": 2,
"hotel_id": 2
}
]
}
}
]
This sorts the rooms of each hotel per price:
$greatDealsinitial->each(function($deal) {
$deal->hotel->setRelation('room', $deal->hotel->room->sortBy('price'));
});
$greatDeals = $greatDealsinitial->hotel->room->sortBy('price')
if this array looks
[
['price' => 0],
['price' => 1],
['price' => 3]
]

How to filter laravel collection from given data

i have a collection data
{
"success": true,
"doctor": [
{
"id": 1,
"name": "Dr. Mayank",
"dob": "1975-01-01",
"about": "This is description",
"status": 1,
"rating": 2,
"rating_given_by": 1,
"alternative_number": "7686876876",
"profile_photo": [],
"speciality": [
{
"id": 3,
"name": "Acupuncture",
"image": null,
"dashboard_flag": 1
},
{
"id": 4,
"name": "Acupuncturist",
"image": null,
"dashboard_flag": 1
},
{
"id": 1,
"name": "Accident and emergency medicine",
"image": "http://192.168.16.21/remidify/media/174/detail.png",
"dashboard_flag": 1
}
],
"service": [
{
"id": 78,
"name": "Correction of gummy smile",
"cost": "12.00"
},
{
"id": 77,
"name": "Dental aesthetics",
"cost": "43.00"
}
],
"clinics": [
{
"id": 1,
"name": "akram",
"entity_id": 1,
"entity_type": "App\Doctor",
"contact_number": "2132132132132",
"status": 0,
"consultancy_fee": "12.00",
"available_today": "No",
"owner_name": "Dr. Mayank",
"pivot": {
"doctor_id": 1,
"clinic_id": 1
},
"address": {
"id": 1,
"address_1": "asdasdasdsa",
"address_2": "",
"locality": "downtown",
"city": "noida",
"state": "up",
"postal_code": "41561566"
},
"speciality": [],
"service": [
{
"id": 11,
"name": "Laminates",
"cost": "20.00"
},
{
"id": 12,
"name": "Dental surgery",
"cost": "300.00"
}
],
"clinic_image": [
{
"id": 7,
"model_id": 1,
"model_type": "App\Clinic",
"collection_name": "clinic_image",
"file_name": "1494863957588.566162.jpg",
"disk": "media",
"url": "http://192.168.16.21/remidify/media/7/1494863957588.566162.jpg"
}
],
"id_image": [
{
"id": 8,
"model_id": 1,
"model_type": "App\Clinic",
"collection_name": "id_image",
"file_name": "1494863966218.348877.jpg",
"disk": "media",
"url": "http://192.168.16.21/remidify/media/8/1494863966218.348877.jpg"
}
],
"location": {
"id": 1,
"latitude": 0,
"longitude": 0,
"entity_id": 1,
"entity_type": "App\Clinic",
"created_at": "2017-05-16 03:00:10",
"updated_at": "2017-05-16 03:00:10"
},
"clinic_timings": [
{
"day": "sun",
"opens_at": "09:28:00",
"closes_at": "21:28:00"
}
]
}
],
"education": [
{
"id": 19,
"degree": "MBBS",
"university": "Univercity",
"year": "2017",
"entity_id": 1,
"entity_type": "App\Doctor",
"created_at": "2017-05-16 05:44:11",
"updated_at": "2017-05-16 05:44:11",
"location": "Delhi"
}
],
"experience": [
{
"id": 19,
"hospital": "Hospital name",
"post": "pta ni hai",
"from": "1970-01-01",
"to": "0000-00-00",
"entity_id": 1,
"entity_type": "App\Doctor",
"created_at": "2017-05-16 05:44:12",
"updated_at": "2017-05-16 05:44:12",
"location": "Locations12",
"is_currently_working": 1
}
],
"registration": {
"id": 1,
"registration_number": "Reg # 2324324",
"registration_year": 1975,
"registration_council": "Council",
"experience": null,
"doctor_id": 1,
"created_at": "2017-05-16 02:56:37",
"updated_at": "2017-05-16 02:56:37",
"adhaar_number": "232131231232",
"id_proof": [
{
"id": 2,
"model_id": 1,
"model_type": "App\DoctorRegistration",
"collection_name": "id_proof",
"file_name": "1494863680447.329102.jpg",
"disk": "media",
"url": "http://192.168.16.21/remidify/media/2/1494863680447.329102.jpg"
}
],
"registration_proof": [
{
"id": 3,
"model_id": 1,
"model_type": "App\DoctorRegistration",
"collection_name": "registration_proof",
"file_name": "1494863687436.266846.jpg",
"disk": "media",
"url": "http://192.168.16.21/remidify/media/3/1494863687436.266846.jpg"
}
],
"qualification_proof": [
{
"id": 4,
"model_id": 1,
"model_type": "App\DoctorRegistration",
"collection_name": "qualification_proof",
"file_name": "1494863695576.803955.jpg",
"disk": "media",
"url": "http://192.168.16.21/remidify/media/4/1494863695576.803955.jpg"
}
]
},
"preference": {
"availability": 1,
"appointment_confirmation_method": "manual",
"average_time": 7,
"holiday_from": null,
"holiday_till": null,
"patients_per_hour": null,
"preferred_appointment_type": "timeslot",
"appointment_frequency": null,
"preferred_payment_method": [
{
"payment_method": "cash"
},
{
"payment_method": "online"
}
]
},
"user": null,
"doctor_clinic": [
{
"doctor_id": 1,
"clinic_id": 1,
"consultancy_fee": "12.00",
"deleted_at": null,
"workdays": [
{
"day": "sun",
"available": 1,
"workhours": [
{
"from": "09:28:00",
"to": "21:28:00"
}
]
}
],
"service": []
}
]
}
]
}
Now how can i find the doctors whose "about or specialty name" matches with some given search string.
Thanks in advance.
Try using dd() helper and use like this below
$youcollectionvariables = { "success": true, "doctor": [ { "id": 1, "name": "Dr. Mayank", "dob": "1975-01-01"................. }
dd($youcollectionvariables)
you will see a formatted data and can find what you need clearly.
Hope that helps.

How to filter a tree like array by a specific field using Laravel Eloquent

This is my result tree which I want to filter by 'language_code' field
"theme_detail": [
{
"id": 1,
"parent_theme_id": null,
"image_url": "no_image",
"index_value": 1,
"status": "active",
"theme_detail": [
{
"id": 4,
"theme_id": 1,
"language_code": "bn",
"theme_name": "থিম 1",
"theme_subtitle": "থিম 1 উপশিরোনাম",
"status": "active"
},
{
"id": 1,
"theme_id": 1,
"language_code": "en",
"theme_name": "Theme 1",
"theme_subtitle": "Theme 1 Subtitle",
"status": "active"
}
],
"parent_recursive": [
{
"id": 2,
"parent_theme_id": 1,
"image_url": "no_image",
"index_value": 1,
"status": "active",
"theme_detail": [
{
"id": 5,
"theme_id": 2,
"language_code": "bn",
"theme_name": "থিম 2",
"theme_subtitle": "থিম 2 উপশিরোনাম",
"status": "active"
},
{
"id": 2,
"theme_id": 2,
"language_code": "en",
"theme_name": "Theme 2",
"theme_subtitle": "Theme 2 Subtitle",
"status": "active"
}
],
"parent_recursive": [
{
"id": 3,
"parent_theme_id": 2,
"image_url": "no_image",
"index_value": 1,
"status": "active",
"theme_detail": [
{
"id": 3,
"theme_id": 3,
"language_code": "en",
"theme_name": "Theme 3",
"theme_subtitle": "Theme 3 Subtitle",
"status": "active"
},
{
"id": 6,
"theme_id": 3,
"language_code": "bn",
"theme_name": "থিম 3",
"theme_subtitle": "থিম 3 উপশিরোনাম",
"status": "active"
}
],
"parent_recursive": [
{
"id": 4,
"parent_theme_id": 3,
"image_url": "no_image",
"index_value": 1,
"status": "active",
"theme_detail": [
{
"id": 7,
"theme_id": 4,
"language_code": "bn",
"theme_name": "থিম 4",
"theme_subtitle": "থিম 4 উপশিরোনাম",
"status": "active"
},
{
"id": 9,
"theme_id": 4,
"language_code": "en",
"theme_name": "Theme 4",
"theme_subtitle": "Theme 4 Subtitle",
"status": "active"
}
],
"parent_recursive": []
}
]
},
{
"id": 5,
"parent_theme_id": 2,
"image_url": "no_image",
"index_value": 1,
"status": "active",
"theme_detail": [
{
"id": 8,
"theme_id": 5,
"language_code": "bn",
"theme_name": "থিম 5",
"theme_subtitle": "থিম 5 উপশিরোনাম",
"status": "active"
},
{
"id": 10,
"theme_id": 5,
"language_code": "en",
"theme_name": "Theme 5",
"theme_subtitle": "Theme 5 Subtitle",
"status": "active"
}
],
"parent_recursive": []
}
]
}
]
}
]
This is my json array which is in a tree like structure.
This array is the result of a recursive eloquent relation.
Now I want to filter it by a specific language code or by any other field.
How can I do it using Laravel eloquent?
can anybody help?
Do you want your eventual response to be like this:
'language_code' => [item_list]

How do i get the nested hash within this hash

I am having real difficulty referencing messages within this hash.
[
{
"MessageThreadID": 1,
"CustomerID": 171,
"MessageType": 1,
"Subject": "Test Message",
"OpenDate": "2015-09-17T00:00:00",
"Closed": false,
"ClosedDate": null,
"Messages": [
{
"IBMessageID": 1,
"MessageThreadID": 1,
"MessageText": "Test Message",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-17T17:23:00"
},
{
"IBMessageID": 2,
"MessageThreadID": 1,
"MessageText": "Test this Update",
"FromCustomer": false,
"UserID": 1,
"Date": "2015-09-17T17:23:00"
},
{
"IBMessageID": 3,
"MessageThreadID": 1,
"MessageText": "My New Message",
"FromCustomer": false,
"UserID": 1,
"Date": "2015-09-17T17:23:00"
},
{
"IBMessageID": 4,
"MessageThreadID": 1,
"MessageText": "Reply",
"FromCustomer": false,
"UserID": 1,
"Date": "2015-09-17T17:05:00"
},
{
"IBMessageID": 5,
"MessageThreadID": 1,
"MessageText": "Some sensible shit",
"FromCustomer": false,
"UserID": 1,
"Date": "2015-09-17T17:23:00"
},
{
"IBMessageID": 14,
"MessageThreadID": 1,
"MessageText": "Message 2",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-21T14:10:00"
},
{
"IBMessageID": 16,
"MessageThreadID": 1,
"MessageText": "Message 2",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-22T16:22:00"
},
{
"IBMessageID": 25,
"MessageThreadID": 1,
"MessageText": "Added via abacus\r\n",
"FromCustomer": false,
"UserID": 1,
"Date": "2015-09-22T16:22:00"
},
{
"IBMessageID": 26,
"MessageThreadID": 1,
"MessageText": "sdsdsdsd",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-22T16:40:00"
},
{
"IBMessageID": 27,
"MessageThreadID": 1,
"MessageText": "test",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-22T17:02:00"
},
{
"IBMessageID": 28,
"MessageThreadID": 1,
"MessageText": "test",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-22T17:06:00"
}
]
},
{
"MessageThreadID": 5,
"CustomerID": 171,
"MessageType": 1,
"Subject": "Unit Test Thread",
"OpenDate": "2015-09-21T13:11:00",
"Closed": false,
"ClosedDate": null,
"Messages": [
{
"IBMessageID": 12,
"MessageThreadID": 5,
"MessageText": "Test Message",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-21T13:11:00"
}
]
},
{
"MessageThreadID": 11,
"CustomerID": 171,
"MessageType": 0,
"Subject": "Test5",
"OpenDate": "2015-09-22T14:39:00",
"Closed": false,
"ClosedDate": null,
"Messages": [
{
"IBMessageID": 22,
"MessageThreadID": 11,
"MessageText": "Test5",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-22T14:39:00"
}
]
},
{
"MessageThreadID": 13,
"CustomerID": 171,
"MessageType": 0,
"Subject": "Test6",
"OpenDate": "2015-09-22T14:41:00",
"Closed": false,
"ClosedDate": null,
"Messages": [
{
"IBMessageID": 24,
"MessageThreadID": 13,
"MessageText": "Test6",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-22T14:41:00"
}
]
},
{
"MessageThreadID": 12,
"CustomerID": 171,
"MessageType": 0,
"Subject": "Test5",
"OpenDate": "2015-09-22T14:41:00",
"Closed": false,
"ClosedDate": null,
"Messages": [
{
"IBMessageID": 23,
"MessageThreadID": 12,
"MessageText": "Test5",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-22T14:41:00"
}
]
},
{
"MessageThreadID": 14,
"CustomerID": 171,
"MessageType": 1,
"Subject": "Test",
"OpenDate": "2015-09-23T12:24:00",
"Closed": false,
"ClosedDate": null,
"Messages": [
{
"IBMessageID": 29,
"MessageThreadID": 14,
"MessageText": "Test",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-23T12:24:00"
}
]
},
{
"MessageThreadID": 15,
"CustomerID": 171,
"MessageType": 1,
"Subject": "Accounts Test",
"OpenDate": "2015-09-23T15:35:00",
"Closed": false,
"ClosedDate": null,
"Messages": [
{
"IBMessageID": 30,
"MessageThreadID": 15,
"MessageText": "Accounts Test",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-23T15:35:00"
}
]
},
{
"MessageThreadID": 16,
"CustomerID": 171,
"MessageType": 2,
"Subject": "Savings ",
"OpenDate": "2015-09-23T15:36:00",
"Closed": false,
"ClosedDate": null,
"Messages": [
{
"IBMessageID": 31,
"MessageThreadID": 16,
"MessageText": "Savings",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-23T15:36:00"
}
]
},
{
"MessageThreadID": 17,
"CustomerID": 171,
"MessageType": 2,
"Subject": "Savings ",
"OpenDate": "2015-09-23T15:37:00",
"Closed": false,
"ClosedDate": null,
"Messages": [
{
"IBMessageID": 32,
"MessageThreadID": 17,
"MessageText": "Savings",
"FromCustomer": true,
"UserID": null,
"Date": "2015-09-23T15:37:00"
}
]
}
]
My initial call is performed by the following code:
def open_contact_messages(customer_id)
customer_id = #customer.id
response = get_call('/Messages/GetOpenedMessages/' + customer_id.to_s)
response = JSON.parse(response.body)
prettyresponse = JSON.pretty_generate(response)
#openmessages = {}
#openmessages = response.map do |openmessage|
Contact.new(openmessage)
end
return #openmessages
end
The output shown above is from prettyresponse. In my initializer I have the following code. ibmessages is my attempt at referencing the data within messages but i get a cant convert string into integer error.
class Contact
attr_accessor :message_customer_ID, :message_type, :message_subject, :message_text, :message_source, :message_thread_ID
attr_reader :messages
def initialize(options)
#message_customer_ID = options['CustomerID'].to_s
#message_type = options['MessageType'].to_s
#message_subject = options['Subject'].to_s
#message_source = options['Closed'].to_s
#message_thread_ID = options['MessageThreadID'].to_s
#messages = options['Messages']
end
end
In my view I can output the entire hash but referencing the messages hash is proving difficult.
- open_contact_messages(#customer.id).each do |openmessage|
.message-container
%p.message-intro
Filler said....
.message
%h4.message-header.message-contents= "Message Subject : #{openmessage.message_subject}"
%p.message-body.message-text= "Message Text : #{openmessage.message_text}"
%p.message-body.message-source= "Message Source : #{openmessage.message_source}"
%p.message-body.message-thread-ID= "Message Thread ID #{openmessage.message_thread_ID}"
%p.message-body.message-thread-ID= "Message Test"
%p.message-body.message-thread-ID
- openmessage.messages do |message|
= message['MessageText']
I am getting a variety of errors based on the many approaches I have found online but no solution. The most common error is cannot convert integer to string.
What you have here is an array of arrays, i.e. you have a bunch of message threads, each of them contains a bunch of messages.
With this code
#openmessages = response.map do |openmessage|
Contact.new(openmessage)
end
you create a Contact instance, and provide it a message thread, i.e. this part:
{
"MessageThreadID": 1,
"CustomerID": 171,
"MessageType": 1,
"Subject": "Test Message",
"OpenDate": "2015-09-17T00:00:00",
"Closed": false,
"ClosedDate": null,
"Messages": [ ... ]
}
In your constructor, you may directly assign from options hash only keys listed above, i.e.
#message_customer_ID = options['CustomerID'].to_s # ok
#message_type = options['MessageType'].to_s # ok
#message_subject = options['Subject'].to_s # ok
#message_text = options['MessageText'].to_s # not ok
#message_source = options['Closed'].to_s # ok
#message_thread_ID = options['MessageThreadID'].to_s # ok
#messages = options['Messages'].to_s # not ok
#ibmessages = options['Messages']['IBMessageID'].to_s # not ok
Messages key contains an array of messages, so you can't just convert them to string, but instead you need to store them as array, so you may process them further.
If you want to output an array of your messages, you need to change #messages assigning to an array, like this:
#messages = options['Messages']
Add a reader method to your Contact class:
class Contact
attr_reader :messages
end
And after that you can use this reader in your view:
- openmessage.messages do |message|
= message['MessageText']
Please, note to use - in front of openmessage.messages do |message| line, exactly as in my code above, and not =. The difference between them is that = writes the result to the buffer (i.e. outputs something), while - just runs some ruby code. In this context you don't want to write whole openmessage.messages array in your view in a serialized form, but instead to process it in a loop.

Resources