Mapping data in Laravel - php

I am not able to understand the response for API in Laravel, it is confusing.
I expect this output
{
"month": "January",
"year": 2020,
"history_data": [
{
"id": 27,
"jurnal_id": 12313,
"name": "Transaksi RAHN FLEKSI",
"point": 500,
"status": "SUKSES",
"created_at": "2020-03-18 17:03:26",
"updated_at": "2020-03-18 17:03:26",
},
]
},
{
"month": "February",
"year": 2020,
"history_data": [
{
"id": 27,
"jurnal_id": 1231313,
"name": "Transaksi RAHN FLEKSI",
"point": 500,
"status": "SUKSES",
"created_at": "2020-03-18 17:03:26",
"updated_at": "2020-03-18 17:03:26",
}
],
{
"month": "February",
"year": 2021,
"history_data": [
{
"id": 182,
"jurnal_id": 13213,
"name": "Transaksi RAHN FLEKSI",
"point": 500,
"status": "SUKSES",
"created_at": "2021-02-18 17:03:26",
"updated_at": "2021-02-18 17:03:26",
},
{
"id": 1812313,
"jurnal_id": 12313313,
"name": "Transaksi RAHN FLEKSI",
"point": 500,
"status": "SUKSES",
"created_at": "2021-02-18 17:03:26",
"updated_at": "2021-02-18 17:03:26",
}
]
{
"month": "March",
"year": 2021,
"history_data": [
{
"id": 183,
"jurnal_id": 132313,
"name": "Transaksi RAHN FLEKSI",
"point": 500,
"status": "SUKSES",
"created_at": "2021-03-18 17:03:26",
"updated_at": "2021-03-18 17:03:26",
}
]
}
The 'history_data' is Grouped by year and month if I'm not wrong.
But, I still get response like below
"2021": [
{
"month": "February",
"year": "2021",
"history_data": {
"id": 2,
"id_jurnal": 1846756745650,
"name": "Transaksi ARRUM SAFAR",
"point": 1200,
"status": "SUKSES",
"created_at": "2021-02-13 10:11:21",
"updated_at": "2020-02-13 10:11:21",
"cif_number": "1003002713"
}
},
{
"month": "March",
"year": "2021",
"history_data": {
"id": 29,
"id_jurnal": 1015205749121113,
"name": "Transaksi RAHN FLEKSI",
"point": 500,
"status": "SUKSES",
"created_at": "2021-03-18 17:26:57",
"updated_at": "2020-03-18 17:26:57",
"cif_number": "1015205749"
}
}
],
"2020": [
{
"month": "February",
"year": "2020",
"history_data": {
"id": 1,
"id_jurnal": 1846756745652,
"name": "Transaksi ARRUM SAFAR",
"point": 1200,
"status": "SUKSES",
"created_at": "2020-02-13 09:52:56",
"updated_at": "2020-02-13 09:52:56",
"cif_number": "1003002713"
}
},
]
Here's the PHP / Laravel code
$historyPoints = $this->historyPoint
->select(
DB::raw("REGEXP_REPLACE(to_char(created_at, 'Month'), '\s+$', '') as month"),
DB::raw("date_part('Year', created_at) as year")
)
->groupBy('year', 'month')
->orderBy('year', 'desc')
->get();
$arr = [];
foreach($historyPoints as $historyPoint) {
foreach(HistoryPointAdd::all() as $data) {
$month = date('F', strtotime($data->created_at));
$year = date('Y', strtotime($data->created_at));
if($month == $historyPoint->month && $year == $historyPoint->year) {
$arr[] = [
'month' => $historyPoint->month,
'year' => $historyPoint->year,
'history_data' => $data
];
}
}
}
$makeToCollection = collect($arr)->groupBy('year');
return $this->sendSuccess($this->successMessage, $makeToCollection);
I'm using PostgreSQL for the database.
Thank you very much

The problem is :
$makeToCollection = collect($arr)->groupBy('year');
The groupBy method groups the collection's items by a given key
Just use :
$makeToCollection = collect($arr);
Btw, collection allows you to chain its methods to perform fluent mapping and reducing :
$historyPoints = $this->historyPoint
->select(
DB::raw("REGEXP_REPLACE(to_char(created_at, 'Month'), '\s+$', '') as month"),
DB::raw("date_part('Year', created_at) as year")
)
->groupBy('year', 'month')
->orderBy('year', 'desc')
->get();
/***** Here we go *****/
$makeToCollection = $historyPoints->map(function ($item) {
$history_data = [];
foreach (HistoryPointAdd::all() as $data) {
$month = date('F', strtotime($data->created_at));
$year = date('Y', strtotime($data->created_at));
if ($month == $historyPoint->month && $year == $historyPoint->year) {
$history_data[] = $data;
}
}
$item['history_data'] = $history_data;
return $item;
});
return $this->sendSuccess($this->successMessage, $makeToCollection);

Related

Doctrine Issue - Entities not joining correctly

So I'm having a strange problem with Doctrine that I don't understand and need help with. Essentially, I am running quite a complex query due to the nature of my database and its various joins and for some reason the response when I grab try to grab all records from my database is returning my entities incorrectly.
See my doctrine query below:
$subQuery = $this->_em->createQueryBuilder()
->from(Product::class, 'ex')
->select('ppsi.id')
->join('ex.productSpecificationItems', 'ppsi')
->where('ex.id = p.id');
$subQuery = $subQuery->getDQL();
$subQuery2 = $this->_em->createQueryBuilder()
->from(Product::class, 'ex2')
->select('ppoiv.id')
->join('ex2.productOptionItemValues', 'ppoiv')
->where('ex2.id = p.id');
$subQuery2 = $subQuery2->getDQL();
$subQuery3 = $this->_em->createQueryBuilder()
->from(Product::class, 'ex3')
->select('poie.id')
->join('ex3.productOptionItems', 'poie')
->where('ex3.id = p.id');
$subQuery3 = $subQuery3->getDQL();
$qb = $this->createQueryBuilder('p')
->select('p, pc, psc, i, po, poi, poiv, ps, psi')
->join('p.productCategory', 'pc')
->leftJoin('p.productSubCategory', 'psc')
->leftJoin('p.images', 'i')
->leftJoin('p.productOptions', 'po')
->leftJoin('p.productSpecifications', 'ps')
->leftJoin('ps.productSpecificationItems', 'psi', Join::WITH, 'psi.id IN (' . $subQuery. ')')
->leftJoin('po.productOptionItems', 'poi', Join::WITH, 'poi.id IN (' . $subQuery3. ')')
->leftJoin('poi.productOptionItemValue', 'poiv', Join::WITH, 'poiv.id IN (' . $subQuery2. ')')
->addOrderBy('p.id', 'ASC');
The response of this causes some entities to have the productOptionItemValues either listed under the wrong productOptionItem, just causes blank records to return, or doesn't return them at all. See an example below (as a JSON for clarity):
{
"id": 373,
"name": "test",
"code": "test",
"url": "373-test",
"price": "1.00",
"stock": 1,
"description": "<p>fghfgh mnsdbfksdhfjk sd</p>\n",
"live": false,
"createdAt": "2022-03-17T14:45:35+00:00",
"updatedAt": "2022-03-17T15:12:44+00:00",
"featured": false,
"aggregateReviewScore": null,
"productCategory": {
"id": 2,
"name": "Hex Set Screws",
"url": "hex-set-screws"
},
"productSubCategory": {
"id": 12,
"name": "Nylon",
"url": "nylon"
},
"images": [],
"productOptions": [
{
"id": 1,
"name": "Colour",
"productOptionItems": {
"0": {
"id": 2,
"name": "Black",
"productOptionItemValue": [
{
"id": 1196,
"stock": 1,
"price": "1.00",
"useOwn": false
},
{
"id": 1201,
"stock": 1,
"price": "1.00",
"useOwn": false
},
{
"id": 1198,
"stock": 1,
"price": "1.00",
"useOwn": false
}
]
},
"1": {
"id": 8,
"name": "Yellow",
"productOptionItemValue": [
{
"id": 1197,
"stock": 1,
"price": "1.00",
"useOwn": false
}
]
},
"2": {
"id": 14,
"name": "Light Grey"
},
"3": null,
"4": {
"id": 15,
"name": "Mid Grey"
},
"7": null,
"8": {
"id": 20,
"name": "Light Blue"
},
"11": null,
"12": {
"id": 22,
"name": "Purple"
},
"13": null
}
},
{
"id": 2,
"name": "Pack Size",
"productOptionItems": [
{
"id": 3,
"name": "10",
"productOptionItemValue": [
{
"id": 1180,
"stock": 100,
"price": "10.00",
"useOwn": true
}
]
},
{
"id": 4,
"name": "100",
"productOptionItemValue": [
{
"id": 1181,
"stock": 10,
"price": "1000.00",
"useOwn": true
}
]
}
]
}
],
"productSpecifications": []
}
If I run the same query on a SINGLE product (so the same Doctrine Query as a above just with a p.id = :id WHERE added) it returns absolutely fine. See the response for that below (and the CORRECT response I am looking for):
{
"id": 373,
"name": "test",
"code": "test",
"url": "373-test",
"price": 1,
"stock": 1,
"description": "<p>fghfgh mnsdbfksdhfjk sd</p>\n",
"live": false,
"createdAt": "2022-03-17T14:45:35+00:00",
"updatedAt": "2022-03-17T15:12:44+00:00",
"featured": false,
"aggregateReviewScore": null,
"productCategory": {
"id": 2,
"name": "Hex Set Screws",
"url": "hex-set-screws"
},
"productSubCategory": {
"id": 12,
"name": "Nylon",
"url": "nylon"
},
"images": [],
"productOptions": [
{
"id": 1,
"name": "Colour",
"productOptionItems": [
{
"id": 2,
"name": "Black",
"productOptionItemValue": {
"id": 1196,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 7,
"name": "Red",
"productOptionItemValue": {
"id": 1201,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 8,
"name": "Yellow",
"productOptionItemValue": {
"id": 1197,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 14,
"name": "Light Grey",
"productOptionItemValue": {
"id": 1202,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 15,
"name": "Mid Grey",
"productOptionItemValue": {
"id": 1205,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 20,
"name": "Light Blue",
"productOptionItemValue": {
"id": 1203,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 22,
"name": "Purple",
"productOptionItemValue": {
"id": 1204,
"stock": 1,
"price": 1,
"useOwn": false
}
},
{
"id": 23,
"name": "Natural",
"productOptionItemValue": {
"id": 1198,
"stock": 1,
"price": 1,
"useOwn": false
}
}
]
},
{
"id": 2,
"name": "Pack Size",
"productOptionItems": [
{
"id": 3,
"name": "10",
"productOptionItemValue": {
"id": 1180,
"stock": 100,
"price": 10,
"useOwn": true
}
},
{
"id": 4,
"name": "100",
"productOptionItemValue": {
"id": 1181,
"stock": 10,
"price": 1000,
"useOwn": true
}
}
]
}
],
"productSpecifications": []
}
Any help or ideas would be greatly appreciated!

Laravel Collection ordered by day of the week M-F

I have a Laravel collection grouped by day of the week but they are in the wrong order. I need them ordered by day of the week starting with Monday.
My Controller:
public function getWeeklySchedule()
{
$testSchedule = VolunteerSchedule::all();
$result = $testSchedule->groupBy(['assignment', function ($item) {
return $item['scheduled_days'];
}]);
return $result;
}
The result looks like this:
"Wednesday": {
"kitchen": [
{
"id": 1,
"full_name": "Hipolito Carroll",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
}
],
"driver": [
{
"id": 3,
"full_name": "Prof. Conor Grimes I",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
}
],
"bagger": [
{
"id": 4,
"full_name": "Martine Kemmer Sr.",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
},
{
"id": 10,
"full_name": "Marcellus Walker",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
}
]
},
"Thursday": {
"kitchen": [
{
"id": 1,
"full_name": "Hipolito Carroll",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
},
{
"id": 7,
"full_name": "Leonardo Schaefer V",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
}
],
"driver": [
{
"id": 3,
"full_name": "Prof. Conor Grimes I",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
},
{
"id": 5,
"full_name": "Prof. Pablo Corwin",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
}
],
"bagger": [
{
"id": 6,
"full_name": "Samantha Feil",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
},
{
"id": 10,
"full_name": "Marcellus Walker",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
}
]
},
"Friday": {
"kitchen": [
{
"id": 1,
"full_name": "Hipolito Carroll",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
}
],
"driver": [
{
"id": 3,
"full_name": "Prof. Conor Grimes I",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
},
{
"id": 9,
"full_name": "Miss Eleonore Kutch IV",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
}
],
"bagger": [
{
"id": 4,
"full_name": "Martine Kemmer Sr.",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
},
{
"id": 10,
"full_name": "Marcellus Walker",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
}
]
},
"Tuesday": {
"kitchen": [
{
"id": 2,
"full_name": "Miss Lessie Torphy",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
},
{
"id": 7,
"full_name": "Leonardo Schaefer V",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
}
],
"bagger": [
{
"id": 10,
"full_name": "Marcellus Walker",
"created_at": "2021-11-05T17:33:52.000000Z",
"updated_at": "2021-11-05T17:33:52.000000Z"
}
]
},
"Saturday": {...
Some fields have been removed for brevity. The days of the week are stored as a serialized array in the database. What is the best way to accomplish this?
Just define a custom sort function that uses a map for the days of the week:
$days = ["Monday" => 1, "Tuesday" => 2, "Wednesday" => 3, "Thursday" => 4, "Friday" => 5, "Saturday" => 6, "Sunday" => 7];
$collection = collect(["Friday" => [], "Wednesday" => [], "Tuesday" => []]);
$collection->sortBy(fn($val, $key) => $days[$key]);
dump($collection);
Output:
=> Illuminate\Support\Collection {#4977
all: [
"Tuesday" => [],
"Wednesday" => [],
"Friday" => [],
],
}
So your code becomes:
public function getWeeklySchedule(): Collection
{
$days = ["Monday" => 1, "Tuesday" => 2, "Wednesday" => 3, "Thursday" => 4, "Friday" => 5, "Saturday" => 6, "Sunday" => 7];
return VolunteerSchedule::all()
->groupBy(['assignment', fn ($item) => $item['scheduled_days']])
->sortBy(fn ($val, $key) => $days[$key]);
}
It will 100% work. It will sort collection from monday to sunday.
$ProductAvailabilities =ProductProductAvailability:get();
$days = [
'monday'=>1,
'tuesday'=>2,
'wednesday'=>3,
'thursday'=>4,
'friday'=>5,
'saturday'=>6,
'sunday'=>7
];
$sortingDays = array();
foreach($days as $day => $value)
{
$sortingDays[] = $ProductAvailabilities->where('day_availability',$day);
}
$ProductAvailabilities=collect($sortingDays)->flatten();

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.

Group By Query Builder not returning Object in Laravel

I am having issue with a groupby function. Please i need help.
Here is my code
$rate = Rate::orderBy('created_at', 'desc')->get()->groupBy([function($item) {
return $item->location;
},
function($item) {
return ['currency' => $item->currency];
},
function($item) {
return ['time' => $this->rateTime($item->created_at->format('H'))];
}]
);
This is the result its returning
"data": {
"Lagos": {
"GBP": {
"Afternoon": [
{
"id": 6,
"currency": "GBP",
"buy_rate": "350",
"sell_rate": "450",
"location": "Lagos",
"created_at": "2020-05-25 16:00:41",
"updated_at": "2020-05-25 16:00:41"
}
]
},
"USD": {
"Morning": [
{
"id": 5,
"currency": "USD",
"buy_rate": "390",
"sell_rate": "450",
"location": "Lagos",
"created_at": "2020-05-25 04:04:00",
"updated_at": "2020-05-25 04:04:00"
}
]
},
"EUR": {
"Evening": [
{
"id": 4,
"currency": "EUR",
"buy_rate": "530",
"sell_rate": "545",
"location": "Lagos",
"created_at": "2020-05-21 18:33:30",
"updated_at": "2020-05-21 18:33:30"
}
]
},
"NGN": {
"Afternoon": [
{
"id": 3,
"currency": "NGN",
"buy_rate": "20.45",
"sell_rate": "32.34",
"location": "Lagos",
"created_at": "2020-05-21 16:41:19",
"updated_at": "2020-05-21 16:41:19"
},
{
"id": 2,
"currency": "NGN",
"buy_rate": "20.45",
"sell_rate": "32.34",
"location": "Lagos",
"created_at": "2020-05-21 16:39:15",
"updated_at": "2020-05-21 16:39:15"
}
]
}
},
"Ghana": {
"NGN": {
"Afternoon": [
{
"id": 1,
"currency": "NGN",
"buy_rate": "20.45",
"sell_rate": "32.34",
"location": "Ghana",
"created_at": "2020-05-21 16:38:26",
"updated_at": "2020-05-21 16:38:26"
}
]
}
}
}
}
But this is what i need
"data": {
"Location": "Lagos",
{
"Currency": "GBP" {
"Afternoon": [
{
"id": 6,
"currency": "GBP",
"buy_rate": "350",
"sell_rate": "450",
"location": "Lagos",
"created_at": "2020-05-25 16:00:41",
"updated_at": "2020-05-25 16:00:41"
}
]
},
"Currency": "USD",
{
"Morning": [
{
"id": 5,
"currency": "USD",
"buy_rate": "390",
"sell_rate": "450",
"location": "Lagos",
"created_at": "2020-05-25 04:04:00",
"updated_at": "2020-05-25 04:04:00"
}
]
},
"Currency": "EUR" {
"Evening": [
{
"id": 4,
"currency": "EUR",
"buy_rate": "530",
"sell_rate": "545",
"location": "Lagos",
"created_at": "2020-05-21 18:33:30",
"updated_at": "2020-05-21 18:33:30"
}
]
},
"Currency": "NGN" {
"Afternoon": [
{
"id": 3,
"currency": "NGN",
"buy_rate": "20.45",
"sell_rate": "32.34",
"location": "Lagos",
"created_at": "2020-05-21 16:41:19",
"updated_at": "2020-05-21 16:41:19"
},
{
"id": 2,
"currency": "NGN",
"buy_rate": "20.45",
"sell_rate": "32.34",
"location": "Lagos",
"created_at": "2020-05-21 16:39:15",
"updated_at": "2020-05-21 16:39:15"
}
]
}
},
"Location": "Ghana" {
"Currency": "NGN" {
"Afternoon": [
{
"id": 1,
"currency": "NGN",
"buy_rate": "20.45",
"sell_rate": "32.34",
"location": "Ghana",
"created_at": "2020-05-21 16:38:26",
"updated_at": "2020-05-21 16:38:26"
}
]
}
}
}
}
I want to be get an object with keys and values and not only the values. Been trying diferent ways but still now getting it. I will be glad if someone could be of help to me.

Array in other formate

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

Categories