Array in other formate - php

I am working on restfull api's for mobile app development. I am returning an php array in json which is like,
"data": {
"Waxing": [
{
"id": "119",
"provider_id": "54",
"provider_service_id": "0",
"category_id": "15",
"date": "09-06-2018",
"time": "08.00 AM,10.00 AM,11.00 AM,12.00 PM,01.00 PM,02.00 PM,03.00 PM,04.00 PM,05.00 PM,06.00 PM,07.00 PM",
"repeat": "D",
"deleted_at": null,
"created_at": "2018-06-09 05:22:47",
"updated_at": "2018-06-09 14:22:04",
"setdate": "09 Jun",
"name": "Waxing"
}
],
"Massage": [
{
"id": "145",
"provider_id": "54",
"provider_service_id": "0",
"category_id": "4",
"date": "14-06-2018",
"time": "08.00 AM,09.00 AM,10.00 AM,11.00 AM,12.00 PM,01.00 PM,02.00 PM,03.00 PM,04.00 PM,05.00 PM,06.00 PM,07.00 PM",
"repeat": "O",
"deleted_at": null,
"created_at": "2018-06-13 14:24:15",
"updated_at": "2018-06-13 14:24:15",
"setdate": "14 Jun",
"name": "Massage"
}
]
},
and creating this output with these line of code:
foreach ($getproviderdatetime as $getproviderdatetimes){
$categorycheck = Category::where('id', '=', $getproviderdatetimes->category_id)->first();
if(count($categorycheck)>0){
$alldata[$categorycheck->name][]=$getproviderdatetimes;
}
}
but now I need data in this format:
"data": {
[
"categoryname": "Waxing",
"services": [
{
"id": "119",
"provider_id": "54",
"provider_service_id": "0",
"category_id": "15",
"date": "09-06-2018",
"time": "08.00 AM,10.00 AM,11.00 AM,12.00 PM,01.00 PM,02.00 PM,03.00 PM,04.00 PM,05.00 PM,06.00 PM,07.00 PM",
"repeat": "D",
"deleted_at": null,
"created_at": "2018-06-09 05:22:47",
"updated_at": "2018-06-09 14:22:04",
"setdate": "09 Jun",
"name": "Waxing"
}
]
],
[
"categoryname": "massage",
"services": [
{
"id": "145",
"provider_id": "54",
"provider_service_id": "0",
"category_id": "4",
"date": "14-06-2018",
"time": "08.00 AM,09.00 AM,10.00 AM,11.00 AM,12.00 PM,01.00 PM,02.00 PM,03.00 PM,04.00 PM,05.00 PM,06.00 PM,07.00 PM",
"repeat": "O",
"deleted_at": null,
"created_at": "2018-06-13 14:24:15",
"updated_at": "2018-06-13 14:24:15",
"setdate": "14 Jun",
"name": "Massage"
}
]
]
},
I have array of services and getting category name from database. I am using Laravel framework and returning data in json format. How can I achive this. Need help.

Here's the solution:
foreach ($getproviderdatetime as $getproviderdatetimes){
$categorycheck = Category::where('id', '=', $getproviderdatetimes->category_id)->first();
if(count($categorycheck)>0){
// append new item to all data:
$alldata[] = [
"categoryname" => $categorycheck->name,
"services" => [$getproviderdatetimes],
];
}
}

$testing = []
foreach ($alldata as $key=>$all){
array_push($testing,["categoryname"=>$key,"services"=>$all]);
}
print_r($testing);
Loop again ur $alldata..Bellow is ur solution
https://3v4l.org/9iT9l

Related

Laravel Eloquent perform Aggregation function in the pivot relationship

I would like to perform the average rating of respective product which stored in the pivot table called "reviews".Below are my existing code.
Product Model:
public function reviews(){
return $this->belongsToMany(User::class,'reviews')->withPivot('comment','rating')->withTimestamps();
}
public function getProductRatingAttribute(){
return $this->reviews()->average('rating');
}
User Model:
public function reviews(){
return $this->belongsToMany(Product::class,'reviews')->withPivot('comment','rating')->withTimestamps();
}
Migration for the reviews
Schema::create('reviews', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('product_id');
$table->string('comment')->nullable();
$table->integer('rating');
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('product_id')->references('id')->on('products');
});
I have attempted to use the below to code construct the expected output but it leads N+1 issue because it does not take advantage of the eager loading of the Laravel Eloquent.
$s = Product::with('reviews')->append('product_rating');
As I check telescope, it produces 6 query which can lead performance issue when the data is large.
Expected output:
{
"msg": [
{
"id": 4,
"created_at": "2021-04-09T07:32:35.000000Z",
"updated_at": "2021-04-09T07:32:35.000000Z",
"name": "MacDonald",
"nickname": "MCD",
"users_id": 1,
"price": "0.00",
"product_rating": "3.3333",
"reviews": [
{
"id": 1,
"name": "John Smith",
"email": "john.smith#hotmail.com",
"email_verified_at": null,
"created_at": "2021-04-08T13:29:13.000000Z",
"updated_at": "2021-04-08T13:29:13.000000Z",
"role": 0,
"pivot": {
"product_id": 4,
"user_id": 1,
"comment": "Ouch",
"rating": 3,
"created_at": "2021-05-01T11:51:26.000000Z",
"updated_at": "2021-05-01T11:52:07.000000Z"
}
},
{
"id": 2,
"name": "Kelvin Ooi",
"email": "kelvin.ooi#hotmail.com",
"email_verified_at": null,
"created_at": "2021-04-08T13:29:13.000000Z",
"updated_at": "2021-04-13T12:07:11.000000Z",
"role": 1,
"pivot": {
"product_id": 4,
"user_id": 2,
"comment": "Ouch",
"rating": 5,
"created_at": "2021-05-01T11:51:26.000000Z",
"updated_at": "2021-05-01T11:52:07.000000Z"
}
},
{
"id": 1,
"name": "John Smith",
"email": "john.smith#hotmail.com",
"email_verified_at": null,
"created_at": "2021-04-08T13:29:13.000000Z",
"updated_at": "2021-04-08T13:29:13.000000Z",
"role": 0,
"pivot": {
"product_id": 4,
"user_id": 1,
"comment": "Ouch",
"rating": 2,
"created_at": "2021-05-01T11:51:26.000000Z",
"updated_at": "2021-05-01T11:52:07.000000Z"
}
}
]
},
{
"id": 10,
"created_at": null,
"updated_at": null,
"name": "Mary Bown",
"nickname": "MB",
"users_id": 1,
"price": "2.88",
"product_rating": "2.0000",
"reviews": [
{
"id": 1,
"name": "John Smith",
"email": "john.smith#hotmail.com",
"email_verified_at": null,
"created_at": "2021-04-08T13:29:13.000000Z",
"updated_at": "2021-04-08T13:29:13.000000Z",
"role": 0,
"pivot": {
"product_id": 10,
"user_id": 1,
"comment": "Ouch",
"rating": 2,
"created_at": "2021-05-01T11:51:26.000000Z",
"updated_at": "2021-05-01T11:52:07.000000Z"
}
}
]
},
{
"id": 11,
"created_at": null,
"updated_at": null,
"name": "Pizza Hut",
"nickname": "pizzahut",
"users_id": 1,
"price": "4.10",
"product_rating": null,
"reviews": [
]
},
{
"id": 12,
"created_at": "2021-04-09T08:00:42.000000Z",
"updated_at": "2021-04-09T08:00:42.000000Z",
"name": "Domino Pizza",
"nickname": "domino",
"users_id": 3,
"price": "0.00",
"product_rating": null,
"reviews": [
]
},
{
"id": 13,
"created_at": "2021-04-26T16:12:53.000000Z",
"updated_at": "2021-04-26T16:12:53.000000Z",
"name": "Chicken Chop",
"nickname": "chickchop",
"users_id": 3,
"price": "0.00",
"product_rating": null,
"reviews": [
]
}
]
}
Appending is performing the query on each record.
Why not perform average on the collection itself?
$s = Product::with('reviews')->get();
$avg = $s->avg('pivot.rating');
Alternatively you can modify the relationship method to include a raw select of the average rating.

how to do pagination complex array in cakephp rest-api?

CakePHP Rest-API pagination in an array of array. Like, containable model pagination in CakePHP for reducing API load.
Some existing code :
$this->request->data['page'];
$data = $this->Model1->find('all',array(
'contain' => array('Model2'),
'fields' => array(),
'conditions' => array('Model1.status' => 1 )
));
Below API response and I want to paginate in ProductUser array because when lots of product load at one-time app will be hang. It's possible or any other way to reduce data load in CakePHP.
API Response :
"status": true,
"message": "Available devices!",
"data": [
{
"id": "6",
"name": "Television",
"parent_id": "0",
"image": "",
"status": "1",
"created": "2019-06-10 15:22:44",
"modified": "2019-06-10 15:22:44",
"ProductUser": [ //Paginate this array
{
"id": "1",
"user_id": "17",
"category_id": "6",
"brand_id": "1",
"product_id": "17",
"date_of_purchase": "2019-06-22",
"seller_id": "1",
"warranty_year": "0",
"warranty_month": "0",
"warranty_end_date": null,
"purchese_price": null,
"bill_upload": "",
"emi_year": "0",
"emi_month": "0",
"emi_start_date": null,
"emi_end_date": null,
"insurance_company_id": "0",
"insurance_year": "0",
"insurance_month": "0",
"insurance_end_date": null,
"created": "2019-06-22 14:13:01",
"modified": "2019-06-22 14:17:07",
"Product": {
"id": "17",
"category_id": "6",
"brand_id": "1",
"product_code": "Samsung LED TV 39 inch",
"name": "Samsung LED TV 39 inch",
"selling_price": "13000",
"short_description": "Television",
"image": "catalog\/sam39.jpg",
"status": "1",
"created": "2019-05-14 00:00:00",
"modified": "2019-05-14 00:00:00"
}
},
{
"id": "1",
"user_id": "17",
"category_id": "6",
"brand_id": "1",
"product_id": "17",
"date_of_purchase": "2019-06-22",
"seller_id": "1",
"warranty_year": "0",
"warranty_month": "0",
"warranty_end_date": null,
"purchese_price": null,
"bill_upload": "",
"emi_year": "0",
"emi_month": "0",
"emi_start_date": null,
"emi_end_date": null,
"insurance_company_id": "0",
"insurance_year": "0",
"insurance_month": "0",
"insurance_end_date": null,
"created": "2019-06-22 14:13:01",
"modified": "2019-06-22 14:17:07",
"Product": {
"id": "17",
"category_id": "6",
"brand_id": "1",
"product_code": "Samsung LED TV 39 inch",
"name": "Samsung LED TV 39 inch",
"selling_price": "13000",
"short_description": "Television",
"image": "catalog\/sam39.jpg",
"status": "1",
"created": "2019-05-14 00:00:00",
"modified": "2019-05-14 00:00:00"
}
}
]
}]

How to sort the collection on custom condition in laravel 5.7?

I have an api ready that returns the following json response.
Response:
{
"success": true,
"conversation": [{
"id": 37,
"type": "1",
"name": "Sonali",
"created_at": "2019-02-18 13:26:10",
"updated_at": "2019-02-18 20:32:54",
"unread_count": 2,
"chat": {
"id": 357,
"conversation_id": "23",
"type": "text",
"sender_id": "37",
"receiver_id": "39",
"data": "{\"text\":\"hello....\"}",
"delivered_at": "2019-02-20 13:25:27",
"seen_at": null,
"created_at": "2019-02-20 13:25:10",
"updated_at": "2019-02-20 13:25:27",
"sender_name": "Sonali"
}
},
{
"id": 38,
"type": "1",
"name": "Raviraj",
"created_at": "2019-02-18 20:23:55",
"updated_at": "2019-02-18 20:32:47",
"unread_count": 0,
"chat": {
"id": 354,
"conversation_id": "22",
"type": "text",
"sender_id": "39",
"receiver_id": "38",
"data": "{\"text\":\"hey....\"}",
"delivered_at": null,
"seen_at": null,
"created_at": "2019-02-20 13:24:35",
"updated_at": "2019-02-20 13:24:35",
"sender_name": "Nitesh Kesarkar"
}
},
{
"id": 27,
"type": "1",
"name": "Rakesh",
"created_at": "2019-02-01 10:48:19",
"updated_at": "2019-02-07 11:35:10",
"unread_count": 1,
"chat": {
"id": 358,
"conversation_id": "21",
"type": "text",
"sender_id": "27",
"receiver_id": "39",
"data": "{\"text\":\"hello\"}",
"delivered_at": "2019-02-20 13:25:27",
"seen_at": null,
"created_at": "2019-02-20 13:25:24",
"updated_at": "2019-02-20 13:25:27",
"sender_name": "Rakesh Patil"
}
}
]
}
This response consists of list of users and their associated last chat message for currently logged in user. I want to sort this collection according to the latest message first. How can I do that?
Sorting should be based on the chat.created_at field.
Expected Result:
{
"success": true,
"conversation": [
{
"id": 27,
"type": "1",
"name": "Rakesh",
"created_at": "2019-02-01 10:48:19",
"updated_at": "2019-02-07 11:35:10",
"unread_count": 1,
"chat": {
"id": 358,
"conversation_id": "21",
"type": "text",
"sender_id": "27",
"receiver_id": "39",
"data": "{\"text\":\"hello\"}",
"delivered_at": "2019-02-20 13:25:27",
"seen_at": null,
"created_at": "2019-02-20 13:25:24",
"updated_at": "2019-02-20 13:25:27",
"sender_name": "Rakesh Patil"
}
},
{
"id": 37,
"type": "1",
"name": "Sonali",
"created_at": "2019-02-18 13:26:10",
"updated_at": "2019-02-18 20:32:54",
"unread_count": 2,
"chat": {
"id": 357,
"conversation_id": "23",
"type": "text",
"sender_id": "37",
"receiver_id": "39",
"data": "{\"text\":\"hello....\"}",
"delivered_at": "2019-02-20 13:25:27",
"seen_at": null,
"created_at": "2019-02-20 13:25:10",
"updated_at": "2019-02-20 13:25:27",
"sender_name": "Sonali"
}
},
{
"id": 38,
"type": "1",
"name": "Raviraj",
"created_at": "2019-02-18 20:23:55",
"updated_at": "2019-02-18 20:32:47",
"unread_count": 0,
"chat": {
"id": 354,
"conversation_id": "22",
"type": "text",
"sender_id": "39",
"receiver_id": "38",
"data": "{\"text\":\"hey....\"}",
"delivered_at": null,
"seen_at": null,
"created_at": "2019-02-20 13:24:35",
"updated_at": "2019-02-20 13:24:35",
"sender_name": "Nitesh Kesarkar"
}
}
]
}
UPDATE :
Adding these lines worked as expected. Thanks #JCode
$sorted = $chats->sortByDesc('chat.created_at');
$chats = $sorted->values()->all();
You are looking for the sortBy() method.
This will of course work if your JSON output can be turned into a collection via collect()—in a perfect scenario, your chat messages would be a model in Laravel.

ignore null objects of eager loaded data- laravel

I have folowing JSON returned by ORM
[
{
"id": 3,
"name": "Card Department",
"name_burmese": "Card Department",
"is_active": "1",
"created_at": "2014-11-23 07:02:07",
"updated_at": "2014-11-23 07:02:07",
"orm_bank_contact": []
},
{
"id": 1,
"name": "Loan Department",
"name_burmese": "Loan Department",
"is_active": "1",
"created_at": "2014-11-23 07:01:16",
"updated_at": "2015-02-24 09:05:35",
"orm_bank_contact": []
},
{
"id": 4,
"name": "Remittance Department",
"name_burmese": "Remittance Department",
"is_active": "0",
"created_at": "2015-02-24 09:43:25",
"updated_at": "2015-04-17 12:26:07",
"orm_bank_contact": []
},
{
"id": 2,
"name": "Deposit Department",
"name_burmese": "Deposit Department",
"is_active": "1",
"created_at": "2014-11-23 07:01:34",
"updated_at": "2015-04-20 14:04:27",
"orm_bank_contact": [
{
"id": 27,
"bank_department": 2,
"mobile": "9843139168",
"phone": "9843139168",
"email": "shresthabeenu#gmail.com",
"contact_person": "Binu Shrestha",
"address": "No. 416, Mahabandoola Road, Kyauktada Township, Yangon, Myanmar",
"is_active": "1",
"created_at": "2015-04-15 08:50:16",
"updated_at": "2015-04-15 08:50:16",
"bank_id": 13
}
]
}
]
but i just need
[
{
"id": 2,
"name": "Deposit Department",
"name_burmese": "Deposit Department",
"is_active": "1",
"created_at": "2014-11-23 07:01:34",
"updated_at": "2015-04-20 14:04:27",
"orm_bank_contact": [
{
"id": 27,
"bank_department": 2,
"mobile": "9843139168",
"phone": "9843139168",
"email": "shresthabeenu#gmail.com",
"contact_person": "Binu Shrestha",
"address": "No. 416, Mahabandoola Road, Kyauktada Township, Yangon, Myanmar",
"is_active": "1",
"created_at": "2015-04-15 08:50:16",
"updated_at": "2015-04-15 08:50:16",
"bank_id": 13
}
]
}
]
I need to fetch record with child on eager loaded objects
I tried below
$bank_contact = BankDepartment::with(array('OrmBankContact' => function($query) use($bank_id){
$query->where('bank_id', "=", $bank_id)->where('bank_department','>',0);}))
->get();
But no luck.. what is the proper way?
This query should do the job returning only departments with OrmBankContact
BankDepartment::has('OrmBankContact')->get();
See Eloquent docs on querying relations
Model BankDepartment
class BankDepartment extends Eloquent implements UserInterface, RemindableInterface {
public function OrmBankContact(){
return $this->hasMany('OrmBankContact','bank_department','id');
}
}
Model OrmBankContact
class OrmBankContact extends Eloquent implements UserInterface, RemindableInterface {
public function BankDepartment(){
return $this->belongsTo('BankDepartment','bank_department','id');
}
}
In Any controller you can get like this
$OrmBankContact = BankDepartment::with('OrmBankContact')->get();
$OrmBankContact = $OrmBankContact->toArray();
echo '<pre>'; print_r($OrmBankContact); exit;

Extracting values from JSON data

I have the JSON data given below. The 'crop' array contains multiple array of crop price, I want to get average crop price of all districts(using 'district_id').
<i>{
"status": "ok",
"count": 7,
"crop": [
{
"id": "133",
"crop_id": "81",
"price": "45.00",
"description": null,
"user_id": "27",
"block_id": "1",
"longitude": "87.8661808",
"latitude": "23.2340073",
"date": "2014-02-03",
"time": "12:44:43",
"district_id": "1"
},
{
"id": "135",
"crop_id": "81",
"price": "10.50",
"description": null,
"user_id": "27",
"block_id": "1",
"longitude": "87.8662402",
"latitude": "23.2339822",
"date": "2014-02-03",
"time": "12:44:54",
"district_id": "1"
},
{
"id": "143",
"crop_id": "81",
"price": "35",
"description": null,
"user_id": "27",
"block_id": "1",
"longitude": "0.0",
"latitude": "0.0",
"date": "2014-02-03",
"time": "13:12:50",
"district_id": "1"
},
{
"id": "146",
"crop_id": "81",
"price": "85",
"description": null,
"user_id": "27",
"block_id": "1",
"longitude": "0.0",
"latitude": "0.0",
"date": "2014-02-03",
"time": "14:29:07",
"district_id": "1"
},
{
"id": "148",
"crop_id": "81",
"price": "25",
"description": null,
"user_id": "27",
"block_id": "1",
"longitude": "0.0",
"latitude": "0.0",
"date": "2014-02-03",
"time": "14:58:01",
"district_id": "1"
},
{
"id": "132",
"crop_id": "81",
"price": "10",
"description": null,
"user_id": "119",
"block_id": "34",
"longitude": "0.0",
"latitude": "0.0",
"date": "2014-02-03",
"time": "12:41:49",
"district_id": "4"
},
{
"id": "134",
"crop_id": "81",
"price": "12",
"description": null,
"user_id": "119",
"block_id": "34",
"longitude": "0.0",
"latitude": "0.0",
"date": "2014-02-03",
"time": "12:43:50",
"district_id": "4"
}
]
}</i>
Use json_decode method to convert it to an std_class or use the 2nd parameter of this method to convert it to an associated array.
Take a look at http://in1.php.net/json_decode
Once you decode it, you can easily access the variables like accessing properties of a class or as an array object if you are converting to an associated array
First you have too decode the JSON using json_decode function, then access using variables.
Do like this..
//Assign your JSON data to this $json variable as shown in the demo.
$arr = json_decode($json,1);
foreach($arr['crop'] as $arr1)
{
foreach($arr1 as $k=>$v)
{
if($arr1['district_id']==1)
{
$avgpr[] = $arr1['price'];
}
}
}
echo $avgprice = array_sum($avgpr)/count($avgpr);
OUTPUT :
40.1
Demo

Categories