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();
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 days ago.
Improve this question
I need to make new array from another array variable. So I have 3 variable
$transaction
[
{
"id": 2,
"member_id": 19,
"date_start": "2023-03-14",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Lee Rosenbaum"
},
{
"id": 3,
"member_id": 14,
"date_start": "2023-03-31",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Erik Spinka"
},
{
"id": 4,
"member_id": 15,
"date_start": "2023-03-26",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Anabel Monahan"
},
{
"id": 5,
"member_id": 9,
"date_start": "2023-02-21",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Anthony Wilkinson"
},
{
"id": 6,
"member_id": 15,
"date_start": "2023-02-23",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Anabel Monahan"
},
{
"id": 7,
"member_id": 13,
"date_start": "2023-04-08",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Pink Moen"
},
{
"id": 9,
"member_id": 10,
"date_start": "2023-02-23",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Viva Wilkinson"
}
]
$jumlah
[
{
"transaction_id": 2,
"total": "5"
},
{
"transaction_id": 3,
"total": "7"
},
{
"transaction_id": 4,
"total": "2"
},
{
"transaction_id": 5,
"total": "4"
},
{
"transaction_id": 6,
"total": "4"
},
{
"transaction_id": 7,
"total": "2"
},
{
"transaction_id": 9,
"total": "2"
}
]
$tanggal
[
{
"transaction_id": 2,
"tgl_kembali": "2023-05-25"
},
{
"transaction_id": 3,
"tgl_kembali": null
},
{
"transaction_id": 4,
"tgl_kembali": null
},
{
"transaction_id": 5,
"tgl_kembali": null
},
{
"transaction_id": 6,
"tgl_kembali": null
},
{
"transaction_id": 7,
"tgl_kembali": "2023-02-17"
},
{
"transaction_id": 9,
"tgl_kembali": "2023-04-21"
}
]
I need to make a new variabel like $newData
I expected the result should be like this for $newData :
[
{
"id": 2,
"member_id": 19,
"date_start": "2023-03-14",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Lee Rosenbaum",
"tgl_kembali": "2023-05-25",
"total": "5"
},
{
"id": 3,
"member_id": 14,
"date_start": "2023-03-31",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Erik Spinka",
"tgl_kembali": null,
"total": "7"
},
{
"id": 4,
"member_id": 15,
"date_start": "2023-03-26",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Anabel Monahan",
"tgl_kembali": null,
"total": "2"
},
{
"id": 5,
"member_id": 9,
"date_start": "2023-02-21",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Anthony Wilkinson",
"tgl_kembali": null,
"total": "4"
},
{
"id": 6,
"member_id": 15,
"date_start": "2023-02-23",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Anabel Monahan",
"tgl_kembali": null,
"total": "4"
},
{
"id": 7,
"member_id": 13,
"date_start": "2023-04-08",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Pink Moen",
"tgl_kembali": "2023-02-17",
"total": "2"
},
{
"id": 9,
"member_id": 10,
"date_start": "2023-02-23",
"created_at": "2023-02-12T10:03:46.000000Z",
"updated_at": "2023-02-12T10:03:46.000000Z",
"name": "Viva Wilkinson",
"tgl_kembali": "2023-04-21",
"total": "2"
}
]
what I can to solve this problem? I work on php(laravel).For some reason I have not been able to find the answer anywhere. I assume it is possible but I just need to make sure.
const newData = [];
for (const transaction of transactions) {
const jumlah = jumlahs.find(j => j.transaction_id === transaction.id);
const tanggal = tanggals.find(t => t.transaction_id === transaction.id);
newData.push({
id: transaction.id,
member_id: transaction.member_id,
date_start: transaction.date_start,
created_at: transaction.created_at,
updated_at: transaction.updated_at,
name: transaction.name,
total: jumlah.total,
tgl_kembali: tanggal.tgl_kembali
});
}
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.
I need to remove the 'data' key from my collection in Laravel.
This worked for me, but it removed the other keys that I cared to keep, I just need to remove the 'data' key:
return $filteredValues = $collection->values ()->all(); // I remove other keys inside the objects.
My collection return:
$records = Item::where('tienda_id',$id)->where('item.nombre', 'like', "%" . $query . "%")->take(50)->get();
return $collection = new ItemCollection($records);
My ItemCollection.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Support\Facades\Storage;
class ItemCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* #param \Illuminate\Http\Request $request
* #return mixed
*/
public function toArray($request)
{
return $this->collection->transform(function($row, $key) {
return [
'id' => $row->id,
'nombre' => $row->nombre,
'marca_id' => $row->marca_id,
'tienda_id' => $row->tienda_id,
'nombre_marca' => $row->marca->nombre_marca,
'unidad_id' => $row->unidad_id,
'nombre_unidad' => $row->unidad->nombre_unidad,
'tipo_cambio' => $row->tienda->tipocambio,
'categoria_id' => $row->categoria_id,
'stock' => $row->stock,
'moneda' => $row->moneda,
'codigos' => $row->codigos,
'stockminimo' => $row->stockminimo,
'stockmaximo' => $row->stockmaximo,
'impuesto_id' => $row->impuesto_id,
'primer_margen' => $row->primer_margen,
'segundo_margen' => $row->segundo_margen,
'precio' => $row->precio,
'notas' => $row->notas,
'imagen' => url('images/'.$row->imagen),
];
});
}
}
My JSON:
{
"data": [
{
"id": 27,
"nombre": "Nombre de prueba",
"marca_id": 2,
"tienda_id": 2,
"nombre_marca": "marca 2",
"unidad_id": 59,
"nombre_unidad": "NIU",
"tipo_cambio": "3.54",
"categoria_id": 1,
"stock": 100,
"moneda": "$",
"codigos": [
{
"id": 2,
"nombre_codigo": "Codigo",
"tienda_id": 2,
"created_at": "2020-08-03T15:19:11.000000Z",
"updated_at": "2020-08-06T22:38:02.000000Z",
"pivot": {
"item_id": 27,
"codigo_id": 2,
"nombre": "66677kj"
}
},
{
"id": 5,
"nombre_codigo": "CODIGO 2",
"tienda_id": 2,
"created_at": "2020-08-07T20:45:29.000000Z",
"updated_at": "2020-08-07T20:45:29.000000Z",
"pivot": {
"item_id": 27,
"codigo_id": 5,
"nombre": "78877k"
}
}
],
"stockminimo": 1,
"stockmaximo": 100,
"impuesto_id": 1,
"primer_margen": "35.00",
"segundo_margen": "20.00",
"precio": "5.07",
"notas": "jkjkkjkkj",
"imagen": "http://maks.test/images/159692202782450637_121718839341269_2075616741920079872_o.jpg"
},
{
"id": 28,
"nombre": "Aleta de pollo",
"marca_id": 1,
"tienda_id": 2,
"nombre_marca": "marca1x",
"unidad_id": 59,
"nombre_unidad": "NIU",
"tipo_cambio": "3.54",
"categoria_id": 1,
"stock": 5,
"moneda": "S/",
"codigos": [
{
"id": 2,
"nombre_codigo": "Codigo",
"tienda_id": 2,
"created_at": "2020-08-03T15:19:11.000000Z",
"updated_at": "2020-08-06T22:38:02.000000Z",
"pivot": {
"item_id": 28,
"codigo_id": 2,
"nombre": "jhjjkj"
}
},
{
"id": 5,
"nombre_codigo": "CODIGO 2",
"tienda_id": 2,
"created_at": "2020-08-07T20:45:29.000000Z",
"updated_at": "2020-08-07T20:45:29.000000Z",
"pivot": {
"item_id": 28,
"codigo_id": 5,
"nombre": "jkk"
}
}
],
"stockminimo": 6,
"stockmaximo": 88,
"impuesto_id": 1,
"primer_margen": "2.00",
"segundo_margen": "10.00",
"precio": "100.00",
"notas": "jkjkkjjk",
"imagen": "http://maks.test/images/159698573182341068_123146022531884_1345097685962588160_o.jpg"
}
]
}
I need it to look like this:
[
{
"id": 27,
"nombre": "Nombre de prueba",
"marca_id": 2,
"tienda_id": 2,
"nombre_marca": "marca 2",
"unidad_id": 59,
"nombre_unidad": "NIU",
"tipo_cambio": "3.54",
"categoria_id": 1,
"stock": 100,
"moneda": "$",
"codigos": [
{
"id": 2,
"nombre_codigo": "Codigo",
"tienda_id": 2,
"created_at": "2020-08-03T15:19:11.000000Z",
"updated_at": "2020-08-06T22:38:02.000000Z",
"pivot": {
"item_id": 27,
"codigo_id": 2,
"nombre": "66677kj"
}
},
{
"id": 5,
"nombre_codigo": "CODIGO 2",
"tienda_id": 2,
"created_at": "2020-08-07T20:45:29.000000Z",
"updated_at": "2020-08-07T20:45:29.000000Z",
"pivot": {
"item_id": 27,
"codigo_id": 5,
"nombre": "78877k"
}
}
],
"stockminimo": 1,
"stockmaximo": 100,
"impuesto_id": 1,
"primer_margen": "35.00",
"segundo_margen": "20.00",
"precio": "5.07",
"notas": "jkjkkjkkj",
"imagen": "http://maks.test/images/159692202782450637_121718839341269_2075616741920079872_o.jpg"
},
{
"id": 28,
"nombre": "Aleta de pollo",
"marca_id": 1,
"tienda_id": 2,
"nombre_marca": "marca1x",
"unidad_id": 59,
"nombre_unidad": "NIU",
"tipo_cambio": "3.54",
"categoria_id": 1,
"stock": 5,
"moneda": "S/",
"codigos": [
{
"id": 2,
"nombre_codigo": "Codigo",
"tienda_id": 2,
"created_at": "2020-08-03T15:19:11.000000Z",
"updated_at": "2020-08-06T22:38:02.000000Z",
"pivot": {
"item_id": 28,
"codigo_id": 2,
"nombre": "jhjjkj"
}
},
{
"id": 5,
"nombre_codigo": "CODIGO 2",
"tienda_id": 2,
"created_at": "2020-08-07T20:45:29.000000Z",
"updated_at": "2020-08-07T20:45:29.000000Z",
"pivot": {
"item_id": 28,
"codigo_id": 5,
"nombre": "jkk"
}
}
],
"stockminimo": 6,
"stockmaximo": 88,
"impuesto_id": 1,
"primer_margen": "2.00",
"segundo_margen": "10.00",
"precio": "100.00",
"notas": "jkjkkjjk",
"imagen": "http://maks.test/images/159698573182341068_123146022531884_1345097685962588160_o.jpg"
}
]
Thanks in advance for reading me, I hope you can help me solve this problem, thanks!
In AppProvider.php or similar add the following. This will disable data wrapping, for ItemCollections. Thou i would want you to reconsider, if you need to use pagination or meta attributes on your responses, you have no where to put em withouth data wrapping and thats one of the reason it is used.
public function boot()
{
ItemCollection::withoutWrapping();
}
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);
I have this controller which group the Collection by date
public function index() {
$poLists = ( new PurchaseOrder() )
->where( 'needed_quantity', '>', 0 )
->where( 'supplier_id', $this->guard()->user()->id )
->get()->groupBy( function ( $item ) {
return [ $item->created_at->format( 'Y-m-d HH:mm:ss' ) ];
} );
return response()->json( $poLists, 200 );
}
working fine and this is the output
{
"2019-02-18 1212:0202:3939": [
{
"id": 2,
"created_at": "2019-02-18 12:16:39",
"updated_at": "2019-02-18 12:16:39"
}
],
"2019-02-18 1515:0202:0202": [
{
"id": 4,
"created_at": "2019-02-18 15:21:02",
"updated_at": "2019-02-18 15:21:02"
},
{
"id": 5,
"created_at": "2019-02-18 15:21:02",
"updated_at": "2019-02-18 15:21:02"
}
],
is there is a way to add static key for each group like
{
date: "2019-02-18 1212:0202:3939" [
{
"id": 2,
"created_at": "2019-02-18 12:16:39",
"updated_at": "2019-02-18 12:16:39"
}
],
date: "2019-02-18 1515:0202:0202": [
{
"id": 3,
"barcode": 33254,
"status": 0,
"created_at": "2019-02-18 15:21:02",
"updated_at": "2019-02-18 15:21:02"
},
{
"id": 5,
"created_at": "2019-02-18 15:21:02",
"updated_at": "2019-02-18 15:21:02"
}
],
Here is date is the static key
Wrap your $poList results data with array with desired key:
$results = [
'date' => $poLists
];
return response()->json($results, 200);
Now, in $results['date'] have all data grouped by date:
{
"date": [
"2019-02-18 1212:0202:3939" [
{
"id": 2,
"created_at": "2019-02-18 12:16:39",
"updated_at": "2019-02-18 12:16:39"
}
],
"2019-02-18 1515:0202:0202": [
{
"id": 3,
"barcode": 33254,
"status": 0,
"created_at": "2019-02-18 15:21:02",
"updated_at": "2019-02-18 15:21:02"
},
{
"id": 5,
"created_at": "2019-02-18 15:21:02",
"updated_at": "2019-02-18 15:21:02"
}
]
]
}
Is this what you are looking for?