Laravel resource groupby the result - php

I have resource API that gives me the result but I want to group them based on relationship model.
Code
controller
$outlet = Outlet::where('slug', $slug)->with(['barcodes.product', 'damages', 'images'])->first();
result
{
"data": {
"id": 1,
"name": "Outlet One",
"slug": "outlet-one",
"address": "Jl Raya Bogor No.200",
"cover": null,
"phone": "0211111112",
"products": [
{
"id": 1,
"sku": "AB001SU",
"serial_number": 5245412185,
"price": 120000,
"discount": null,
"product": {
"id": 1,
"name": "Product One",
"slug": "product-one",
"stock": "70",
"cover": null,
"description": "This is first product description.",
"sku": "AB001SU",
"price": 120000,
"discount": null
}
},
{
"id": 2,
"sku": "FD51",
"serial_number": 778516,
"price": 75300,
"discount": 5300,
"product": {
"id": 1,
"name": "Product One",
"slug": "product-one",
"stock": "70",
"cover": null,
"description": "This is first product description.",
"sku": "AB001SU",
"price": 120000,
"discount": null
}
},
{
"id": 3,
"sku": "7609FS",
"serial_number": 232547544,
"price": 35900,
"discount": null,
"product": {
"id": 2,
"name": "Product Two",
"slug": "product-two",
"stock": "120",
"cover": null,
"description": "This is second product description.",
"sku": "FRY8016",
"price": 450000,
"discount": 50000
}
}
]
},
"message": "Outlet retrieved successfully."
}
As you can see in products": [...] id 1 and 2 are belong to Product One is that possible for me to group by my barcodes.product based on product model?
Update
To be more clear; What I'm looking for is something like this:
{
"data": {
"id": 1,
"name": "Outlet One",
"slug": "outlet-one",
"address": "Jl Raya Bogor No.200",
"cover": null,
"phone": "0211111112",
"products": [
{
"id": 1,
"name": "Product One",
"slug": "product-one",
"stock": "70",
"cover": null,
"description": "This is first product description.",
"sku": "AB001SU",
"price": 120000,
"discount": null
"barcodes": { // now barcodes are grouped by prodcuts
"id": 1,
"sku": "AB001SU",
"serial_number": 5245412185,
"price": 120000,
"discount": null,
},
{
"id": 2,
"sku": "FD51",
"serial_number": 778516,
"price": 75300,
"discount": 5300,
},
},
{
"id": 2,
"name": "Product Two",
"slug": "product-two",
"stock": "120",
"cover": null,
"description": "This is second product description.",
"sku": "FRY8016",
"price": 450000,
"discount": 50000
"barcodes": { // now barcodes are grouped by prodcuts
"id": 3,
"sku": "7609FS",
"serial_number": 232547544,
"price": 35900,
"discount": null,
}
}
]
},
"message": "Outlet retrieved successfully."
}
Update 2
Outlet model
public function barcodes()
{
return $this->belongsToMany(Barcode::class, 'outlet_products');
}
Barcode model
public function outlets()
{
return $this->belongsToMany(Outlet::class, 'outlet_products');
}
public function product()
{
return $this->belongsTo(Product::class);
}

Never tried something like this but you maybe could do this in your Outlet model
use App\Http\Resources\ProductsResource;
public function getProductsAttribute()
{
$barcodes = $this->barcodes
->loadMissing('product')
->makeHidden('product');
$products = $barcodes->pluck('product')->keyBy('id');
$groupedBarcodes = $barcodes->groupBy(function ($barcode) {
return $barcode->product->id;
});
return ProductsResource::collection($products->map(function ($product, $id) use ($groupedBarcodes) {
return $product->setAttribute('barcodes', $groupedBarcodes[$id]);
}))->resolve();
}
What is your resource output with that?

In your Outlet Model write this
public function products(){
return $this->hasMany(Product::class, 'product_id','id');
}
In your Product Model write this
public function barcodes(){
return $this->hasMany(Barcode::class,'barcode_id','id');
}
Then for your query just write this
$outlet = Outlet::where('slug', $slug)->products()->barcodes()->with(['your_field'])->first();

Related

The avalara JSON request not working using PHP cURL but working in postman

I have created a JSON for avalara request, line items are 10 in count. But it is always showing error as -
code:ErrorCountLimitExceededError
number:1722
message : The request has exceeded the maximum number of validation errors.
When I reduce the line item to count 6, it works fine. but my requirement is more than that.
The same JSON is working fine in postman.
Following is the JSON which I had used-
{
"lines": [
{
"number": "1",
"quantity": 1,
"amount": 100,
"taxCode": "PS081282",
"itemCode": "Y0001GHGH",
"description": "TEST"
},
{
"number": "2",
"quantity": 1,
"amount": 100,
"taxCode": "PS081282A",
"itemCode": "TTTTYYYA",
"description": "TEST"
},
{
"number": "3",
"quantity": 1,
"amount": 190,
"taxCode": "PS081282B",
"itemCode": "HGHGHG0001B",
"description": "TEST"
},
{
"number": "4",
"quantity": 1,
"amount": 2300,
"taxCode": "PS081282C",
"itemCode": "PKOO0001C",
"description": "TEST"
},
{
"number": "5",
"quantity": 1,
"amount": 200,
"taxCode": "PS081282D",
"itemCode": "ABCF567",
"description": "TEST"
},
{
"number": "6",
"quantity": 1,
"amount": 10990,
"taxCode": "PS081282E",
"itemCode": "Y00DSD01E",
"description": "TEST"
},
{
"number": "7",
"quantity": 1,
"amount": 140,
"taxCode": "PS081282F",
"itemCode": "Y00GJG232",
"description": "TEST"
},
{
"number": "8",
"quantity": 1,
"amount": 100,
"taxCode": "PS081282F2X",
"itemCode": "65HGFH675",
"description": "TEST"
}
],
"type": "SalesInvoice",
"companyCode": "DEFAULT",
"date": "2023-01-10",
"customerCode": "ABC",
"purchaseOrderNo": "2023-01-10-001",
"addresses": {
"singleLocation": {
"line1": "2000 Main Street",
"city": "Irvine",
"region": "CA",
"country": "US",
"postalCode": "92614"
}
},
"commit": true,
"currencyCode": "USD",
"description": "Yarn"
}

How to return unique values in laravel

Here I have this sample data which returns based on category products and I need to limit repeated values.
Raw JSON
[{
"brand": {
"id": "fe877b45-8620-453a-8805-63f0cbd80752",
"name": "No Brand",
"slug": "no-brand",
"description": "null"
},
"options": [{
"id": "324af955-1aa9-42ea-be6e-bb4e5623a97a",
"parent_id": "null",
"name": "Need Insurance?"
},
{
"id": "73298c18-4ccc-4138-afa5-71d3d00dff9b",
"parent_id": "null",
"name": "Color",
"slug": "color"
}
],
"rating": [],
"tags": [{
"id": "8a31ee4c-3302-4357-9686-bd4308bbf39f",
"name": "options",
"slug": "options",
"photo": "null"
}],
"variations": [{
"id": "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3",
"parent_id": "null",
"name": "Ram",
"slug": "ram",
"photo": "null"
},
{
"id": "e5c70766-a558-4539-b41f-77f72c819a7c",
"parent_id": "null",
"name": "cpu",
"slug": "cpu",
"photo": "null"
},
{
"id": "e63ac831-f595-4889-83d2-a5be65734758",
"parent_id": "null",
"name": "Monitor",
"slug": "monitor"
}
]
},
{
"brand": {
"id": "fe877b45-8620-453a-8805-63f0cbd80752",
"name": "No Brand",
"slug": "no-brand",
"description": null
},
"options": [{
"id": "522da418-eb3f-43e9-9392-63c941842a52",
"parent_id": null,
"name": "Color",
"slug": "color-3"
}],
"rating": [],
"tags": [],
"variations": [{
"id": "8e9a26c5-2ee4-4d86-9244-a10596d67fea",
"parent_id": null,
"name": "cpu",
"slug": "cpu-3",
"photo": null
}]
}
]
Sample data
filters: [{,…}, {,…}]
0: {,…}
brand: {id: "fe877b45-8620-453a-8805-63f0cbd80752", name: "No Brand", slug: "no-brand", description: null,…}
options: [{id: "324af955-1aa9-42ea-be6e-bb4e5623a97a", parent_id: null, name: "Need Insurance?",…},…]
0: {id: "324af955-1aa9-42ea-be6e-bb4e5623a97a", parent_id: null, name: "Need Insurance?",…}
1: {id: "73298c18-4ccc-4138-afa5-71d3d00dff9b", parent_id: null, name: "Color", slug: "color",…}
rating: []
tags: [{id: "8a31ee4c-3302-4357-9686-bd4308bbf39f", name: "options", slug: "options", photo: null,…},…]
variations: [,…]
0: {id: "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3", parent_id: null, name: "Ram", slug: "ram", photo: null,…}
1: {id: "e5c70766-a558-4539-b41f-77f72c819a7c", parent_id: null, name: "cpu", slug: "cpu", photo: null,…}
2: {id: "e63ac831-f595-4889-83d2-a5be65734758", parent_id: null, name: "Monitor", slug: "monitor",…}
1: {,…}
brand: {id: "fe877b45-8620-453a-8805-63f0cbd80752", name: "No Brand", slug: "no-brand", description: null,…}
options: [{id: "522da418-eb3f-43e9-9392-63c941842a52", parent_id: null, name: "Color", slug: "color-3",…}]
0: {id: "522da418-eb3f-43e9-9392-63c941842a52", parent_id: null, name: "Color", slug: "color-3",…}
rating: []
tags: [,…]
variations: [,…]
0: {id: "8e9a26c5-2ee4-4d86-9244-a10596d67fea", parent_id: null, name: "cpu", slug: "cpu-3", photo: null,…}
Explanation
As you can see each of my products has same fields of data and some of them are the same, for instance in options both products have Color or in variations both have cpu or brand of both is the same, in final results I need to have only 1 Color and 1 cpu and 1 brand as they are the same.
code
This is how code above returns
$data = [];
foreach($products as $i => $product) {
$data[$i]['brand'] = $product->brand;
$data[$i]['rating'] = $product->rating;
$data[$i]['variations'] = $product->variations;
$data[$i]['options'] = $product->options;
$data[$i]['tags'] = $product->tags;
}
Note: the final result is a merge of all products data into single array, but unique values. That's what I'm looking for.
Any idea?
Update
sample of final result would be something like this
finalResult: [{,…}, {,…}]
0: {,…}
brand: {id: "fe877b45-8620-453a-8805-63f0cbd80752", name: "No Brand", slug: "no-brand", description: null,…}
0: {id: "fe877b45-8620-453a-8805-63f0cbd80752", name: "No Brand", slug: "no-brand", description: null,…},…] // it was same in both products
options: [{id: "324af955-1aa9-42ea-be6e-bb4e5623a97a", parent_id: null, name: "Need Insurance?",…},…]
0: {id: "324af955-1aa9-42ea-be6e-bb4e5623a97a", parent_id: null, name: "Need Insurance?",…}
1: {id: "73298c18-4ccc-4138-afa5-71d3d00dff9b", parent_id: null, name: "Color", slug: "color",…} // it was same in both products
rating: []
tags: [{id: "8a31ee4c-3302-4357-9686-bd4308bbf39f", name: "options", slug: "options", photo: null,…},…]
0: {id: "8a31ee4c-3302-4357-9686-bd4308bbf39f", name: "options", slug: "options", photo: null,…}
1: {id: "94ef99b6-ed2a-4eea-9248-e4775159eb58", name: "product", slug: "product", photo: null,…}
2: {id: "378802b3-d13a-48c4-afa2-f9fed94d69ee", name: "werg", slug: "werg", photo: null, active: "yes",…} // added from another product
3: {id: "f1380f50-af59-4f6a-8eca-d40689c1c1c1", name: "werwg", slug: "werwg", photo: null, active: "yes",…} // added from another product
variations: [,…]
0: {id: "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3", parent_id: null, name: "Ram", slug: "ram", photo: null,…}
1: {id: "e5c70766-a558-4539-b41f-77f72c819a7c", parent_id: null, name: "cpu", slug: "cpu", photo: null,…} // it was same in both products
2: {id: "e63ac831-f595-4889-83d2-a5be65734758", parent_id: null, name: "Monitor", slug: "monitor",…}
Update 2
Getting children of data
Options and Variations both have children (i.e Cpu => [Core i7, Core i3]) or color => ['red', 'black'] so I need to collect this children's and put them under their parents data.
Option model
public function options()
{
return $this->hasMany(Option::class);
}
public function children() {
return $this->hasMany(Option::class,'parent_id','id') ;
}
public function parent()
{
return $this->belongsTo(Option::class,'parent_id');
}
public function isParent()
{
return !$this->parent_id ? true : false; // if parent_id is null => is a Parent Option
}
Variant model
public function variants()
{
return $this->hasMany(Variant::class);
}
public function children() {
return $this->hasMany(Variant::class,'parent_id','id') ;
}
public function parent()
{
return $this->belongsTo(Variant::class,'parent_id');
}
public function isParent()
{
return !$this->parent_id ? true : false; // if parent_id is null => is a Parent Variant
}
Note: as you probably understand relationship between parent and children are defined by parent_id column.
Sample data (includes all arrays and their childs)
{
"brands": [
{
"id": "fe877b45-8620-453a-8805-63f0cbd80752",
"name": "no brand",
"slug": "no-brand",
"description": null,
"photo": null,
"created_at": "2020-07-15 11:35:18",
"updated_at": "2020-07-15 11:35:18"
}
],
"options": [
{
"id": "324af955-1aa9-42ea-be6e-bb4e5623a97a",
"parent_id": null,
"name": "need insurance?",
"slug": "need-insurance",
"photo": null,
"type": "radio",
"active": "yes",
"created_at": "2020-07-17 11:28:09",
"updated_at": "2020-07-17 11:28:09",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"option_id": "324af955-1aa9-42ea-be6e-bb4e5623a97a"
},
"children": [
{
"id": "44afca9e-abf1-4a7a-9c46-d96d8127c2af",
"parent_id": "324af955-1aa9-42ea-be6e-bb4e5623a97a",
"name": "No",
"slug": "no",
"photo": null,
"type": "radio",
"active": "yes",
"created_at": "2020-07-17 11:28:09",
"updated_at": "2020-07-17 11:28:09"
}
]
},
{
"id": "73298c18-4ccc-4138-afa5-71d3d00dff9b",
"parent_id": null,
"name": "color",
"slug": "color",
"photo": null,
"type": "dropdown",
"active": "yes",
"created_at": "2020-07-17 11:27:41",
"updated_at": "2020-07-17 11:27:41",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"option_id": "73298c18-4ccc-4138-afa5-71d3d00dff9b"
},
"children": [
{
"id": "29b62f35-52a2-4a8b-ac8f-7e70e065488a",
"parent_id": "73298c18-4ccc-4138-afa5-71d3d00dff9b",
"name": "Black",
"slug": "black",
"photo": null,
"type": "dropdown",
"active": "yes",
"created_at": "2020-07-17 11:27:41",
"updated_at": "2020-07-17 11:27:41"
},
{
"id": "4aa2d899-f1cc-4000-95e6-997d28dc51fc",
"parent_id": "73298c18-4ccc-4138-afa5-71d3d00dff9b",
"name": "Red",
"slug": "red",
"photo": null,
"type": "dropdown",
"active": "yes",
"created_at": "2020-07-17 11:27:41",
"updated_at": "2020-07-17 11:27:41"
},
{
"id": "5f9de5bc-e966-48f3-b78c-de709dba86b5",
"parent_id": "73298c18-4ccc-4138-afa5-71d3d00dff9b",
"name": "Gray",
"slug": "gray",
"photo": null,
"type": "dropdown",
"active": "yes",
"created_at": "2020-07-17 11:27:41",
"updated_at": "2020-07-17 11:27:41"
},
{
"id": "f248d6ab-1b88-4ea4-8d6a-62fe271bfa8a",
"parent_id": "73298c18-4ccc-4138-afa5-71d3d00dff9b",
"name": "White",
"slug": "white",
"photo": null,
"type": "dropdown",
"active": "yes",
"created_at": "2020-07-17 11:27:41",
"updated_at": "2020-07-17 11:27:41"
}
]
},
{
"id": "522da418-eb3f-43e9-9392-63c941842a52",
"parent_id": null,
"name": "color",
"slug": "color-3",
"photo": null,
"type": "radio",
"active": "yes",
"created_at": "2020-07-17 12:20:46",
"updated_at": "2020-07-17 12:20:46",
"pivot": {
"product_id": "a8bb27c8-e968-4317-b4d2-8e5cd6049ff8",
"option_id": "522da418-eb3f-43e9-9392-63c941842a52"
},
"children": [
{
"id": "84135f25-690b-407b-8c98-e7526429a594",
"parent_id": "522da418-eb3f-43e9-9392-63c941842a52",
"name": "Red",
"slug": "red-3",
"photo": null,
"type": "radio",
"active": "yes",
"created_at": "2020-07-17 12:20:46",
"updated_at": "2020-07-17 12:20:46"
},
{
"id": "9d1f0d9c-272a-4e96-ac0a-aeac869bfc30",
"parent_id": "522da418-eb3f-43e9-9392-63c941842a52",
"name": "Yellow",
"slug": "yellow-2",
"photo": null,
"type": "radio",
"active": "yes",
"created_at": "2020-07-17 12:20:46",
"updated_at": "2020-07-17 12:20:46"
}
]
}
],
"ratings": [
"4.5",
"4.0"
],
"tags": [
{
"id": "8a31ee4c-3302-4357-9686-bd4308bbf39f",
"name": "options",
"slug": "options",
"photo": null,
"active": "yes",
"created_at": "2020-07-17 11:29:47",
"updated_at": "2020-07-17 11:29:47",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"tag_id": "8a31ee4c-3302-4357-9686-bd4308bbf39f"
}
},
{
"id": "94ef99b6-ed2a-4eea-9248-e4775159eb58",
"name": "product",
"slug": "product",
"photo": null,
"active": "yes",
"created_at": "2020-07-17 11:29:47",
"updated_at": "2020-07-17 11:29:47",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"tag_id": "94ef99b6-ed2a-4eea-9248-e4775159eb58"
}
},
{
"id": "378802b3-d13a-48c4-afa2-f9fed94d69ee",
"name": "werg",
"slug": "werg",
"photo": null,
"active": "yes",
"created_at": "2020-07-15 11:53:13",
"updated_at": "2020-07-15 11:53:13",
"pivot": {
"product_id": "a8bb27c8-e968-4317-b4d2-8e5cd6049ff8",
"tag_id": "378802b3-d13a-48c4-afa2-f9fed94d69ee"
}
},
{
"id": "f1380f50-af59-4f6a-8eca-d40689c1c1c1",
"name": "werwg",
"slug": "werwg",
"photo": null,
"active": "yes",
"created_at": "2020-07-15 11:53:13",
"updated_at": "2020-07-15 11:53:13",
"pivot": {
"product_id": "a8bb27c8-e968-4317-b4d2-8e5cd6049ff8",
"tag_id": "f1380f50-af59-4f6a-8eca-d40689c1c1c1"
}
}
],
"variations": [
{
"id": "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3",
"parent_id": null,
"name": "ram",
"slug": "ram",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 11:27:05",
"updated_at": "2020-07-17 11:27:05",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"variant_id": "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3"
},
"children": [
{
"id": "5687d6a8-12df-41b2-bf2f-b822faae8af0",
"parent_id": "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3",
"name": "4 Gig",
"slug": "4 Gig",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 11:27:05",
"updated_at": "2020-07-17 11:27:05"
}
]
},
{
"id": "e5c70766-a558-4539-b41f-77f72c819a7c",
"parent_id": null,
"name": "cpu",
"slug": "cpu",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 11:26:58",
"updated_at": "2020-07-17 11:26:58",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"variant_id": "e5c70766-a558-4539-b41f-77f72c819a7c"
},
"children": [
{
"id": "83003a24-cc69-4305-8d3a-e99da91d3354",
"parent_id": "e5c70766-a558-4539-b41f-77f72c819a7c",
"name": "Core i7",
"slug": "Core i7",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 11:26:58",
"updated_at": "2020-07-17 11:26:58"
}
]
},
{
"id": "e63ac831-f595-4889-83d2-a5be65734758",
"parent_id": null,
"name": "monitor",
"slug": "monitor",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 11:27:21",
"updated_at": "2020-07-17 11:27:21",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"variant_id": "e63ac831-f595-4889-83d2-a5be65734758"
},
"children": [
{
"id": "816e1fab-24eb-49e9-9b3a-d4b4cce16cdf",
"parent_id": "e63ac831-f595-4889-83d2-a5be65734758",
"name": "14\"",
"slug": "14\"",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 11:27:21",
"updated_at": "2020-07-17 11:27:21"
}
]
},
{
"id": "8e9a26c5-2ee4-4d86-9244-a10596d67fea",
"parent_id": null,
"name": "cpu",
"slug": "cpu-3",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 12:20:56",
"updated_at": "2020-07-17 12:20:56",
"pivot": {
"product_id": "a8bb27c8-e968-4317-b4d2-8e5cd6049ff8",
"variant_id": "8e9a26c5-2ee4-4d86-9244-a10596d67fea"
},
"children": [
{
"id": "50857808-106e-4ae0-8c02-a54761e6dac7",
"parent_id": "8e9a26c5-2ee4-4d86-9244-a10596d67fea",
"name": "Core i3",
"slug": "Core i3-2",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 12:20:56",
"updated_at": "2020-07-17 12:20:56"
}
]
}
]
}
You can achieve what you want in one iteration over the data using reduce like so:
$variations = [];
$result = array_reduce($filters, function ($result, $filter) use ($variations) {
$filter['brand']['name'] = strtolower($filter['brand']['name']);
if ($result['brands']->where('name', $filter['brand']['name'])->isEmpty()) {
$result['brands']->push($filter['brand']);
}
foreach ($filter['options'] as $option) {
$option['name'] = strtolower($option['name']);
if ($result['options']->where('name', $option['name'])->isEmpty()) {
$result['options']->push($option);
}
}
if (isset($filter['rating']['id'])) {
if ($result['ratings']->where('id', $filter['rating']['id'])->isEmpty()) {
$result['ratings']->push($filter['rating']);
}
}
foreach ($filter['tags'] as $tag) {
$tag['name'] = strtolower($tag['name']);
if ($result['tags']->where('name', $tag['name'])->isEmpty()) {
$result['tags']->push($tag);
}
}
foreach ($filter['variations'] as $variation) {
$variation['name'] = strtolower($variation['name']);
$variationName = $variation['name'];
$children = collect($variation['children'])->pluck('name');
if ($result['variations']->where('name', $variation['name'])->isEmpty()) {
$result['variations']->push($variation);
$variations[$variationName] = $children;
} else {
$different = $variations[$variationName]->diff($children);
if ($different->isNotEmpty()) {
$result['variations']->push($variation);
foreach ($different as $childName) {
$variations[$variationName]->push($childName);
}
}
}
}
return $result;
}, collect([
'brands' => collect(),
'options' => collect(),
'ratings' => collect(),
'tags' => collect(),
'variations' => collect()
]));
If you need the result as an array, you can use the collection's toArray method:
$result->toArray();
I have added a sample code with a row json data based on your input
$jsonData = '[{
"brand": {"id": "fe877b45-8620-453a-8805-63f0cbd80752", "name": "No Brand", "slug": "no-brand", "description": "null"},
"options": [{"id": "324af955-1aa9-42ea-be6e-bb4e5623a97a", "parent_id": "null", "name": "Need Insurance?"},
{"id": "73298c18-4ccc-4138-afa5-71d3d00dff9b", "parent_id": "null", "name": "Color", "slug": "color"}],
"rating": [],
"tags": [{"id": "8a31ee4c-3302-4357-9686-bd4308bbf39f", "name": "options", "slug": "options", "photo": "null"}],
"variations": [{"id": "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3", "parent_id": "null", "name": "Ram", "slug": "ram", "photo": "null"},
{"id": "e5c70766-a558-4539-b41f-77f72c819a7c", "parent_id": "null", "name": "cpu", "slug": "cpu", "photo": "null"},
{"id": "e63ac831-f595-4889-83d2-a5be65734758", "parent_id": "null", "name": "Monitor", "slug": "monitor"}
]
},
{
"brand": {"id": "fe877b45-8620-453a-8805-63f0cbd80752", "name": "No Brand", "slug": "no-brand", "description": null},
"options": [{"id": "522da418-eb3f-43e9-9392-63c941842a52", "parent_id": null, "name": "Color", "slug": "color-3"}],
"rating": [],
"tags": [],
"variations": [{"id": "8e9a26c5-2ee4-4d86-9244-a10596d67fea", "parent_id": null, "name": "Cpu", "slug": "cpu-3", "photo": null}]
}
]
';
$jsonDataArr =json_decode($jsonData);
$data = array();
foreach($jsonDataArr as $key => $items){
foreach($items as $innerKey => $eachItem){
if(!isset($data[$innerKey])){
$data[$innerKey] = array();
if(is_array($eachItem)){
foreach($eachItem as $each)
if(!empty($each))
$data[$innerKey][] = (array) $each;
}else{
if(!empty($eachItem))
$data[$innerKey][] = (array) $eachItem;
}
}else{
if(is_array($eachItem)){
foreach($eachItem as $each)
if(!empty($each))
$data[$innerKey][] = (array) $each;
}else{
if(!empty($eachItem))
$data[$innerKey][] = (array) $eachItem;
}
}
}
}
foreach($data as $key => $val){
foreach($val as $l => $item){
$index = trim(strtolower($item['name']));
$data[$key][$index] = $item;
unset($data[$key][$l]);
}
}
foreach($data as $key => $val){
$data[$key]=array_values($val);
}
print_r($data);
Demo

Is it possible extract and merge a single json object from multiple json files?

Sorry for the confusing title. I am having a bit of an issue here merging some JSON files. I need to merge all the products into one array in a separate file.
I have a directory full of same structured json files. I am using glob to select all files and decode->append-->encode json files into one large file.
Here is my code:
<?php
$files = glob("*.json");
$newDataArray = [];
foreach($files as $file){
$thisData = file_get_contents($file);
$thisDataArray = json_decode($thisData);
$newDataArray[] = $thisDataArray;
}
$newDataJSON = json_encode($newDataArray);
file_put_contents("merged.json",$newDataJSON);
?>
Now, the above code seems to work great but I only want to extract all the products.
Quick example of what I need to achieve.
File1.json
{
"status": true,
"user": {
"username": "sally",
"avatar": "/images/default-avatar.png",
"products": [
{
"id": "35vR4hr",
"title": "Picture 1",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "na1Id4t",
"title": "Picture 2",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
}
File2.json
{
"status": true,
"user": {
"username": "Jessica",
"avatar": "/images/default-avatar.png",
"products": [
{
"id": "wjiefi94",
"title": "Picture 3",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 4",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
}
I want the data to be merged like:
merged.json
{
"products": [
{
"id": "wjiefi94",
"title": "Picture 1",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 2",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 3",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 4",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
I hope this makes sense. I feel like I have hit a dead end here. Any help is greatly appreciated.
would it be possible for you to call an external tool like "jq"? handling json (just like csv), especially with many files, is not something you should be doing manually.
btw, your example does not have commas between products 2 and 3 and 3 and 4.
Your new code on line 5 should probably read like this with the array brackets? Otherwise you are overwriting the contents of the last files:
$thisDataArray[] = json_decode($thisData);
And why are you merging products from Sally and Jessica into the same user? Maybe you can just extract all the products objects into one file?
More of a code review than an answer, hope it helps ;)

Podio api - how to set category field when create item

I am using php wrapper, try create an item, all is ok, item is creating, but I can't change status, tried different ways, but can't find right way.
Need change status to "Closed" - http://prntscr.com/fsrwc3
Codes not works:
$fields = new PodioItemFieldCollection([
new PodioCategoryItemField(['external_id'=>'status', 'values'=>13]),
]);
$item = new PodioItem([
'app' => new PodioApp($app_id),
'fields' => $fields
]);
$item->save();
or
$fields = new PodioItemFieldCollection([
new PodioCategoryItemField(['external_id'=>'status', 'values'=>13]),
]);
$item = new PodioItem([
'app' => new PodioApp($app_id),
'fields' => $fields
]);
$item->save();
$get_item = PodioItem::get_basic($item->item_id);
$get_item->fields['status']->values = ['id'=>13];
$get_item->save();
After create item (after new PodioItem...), if I get fields after this code (just get $item->fields or PodioItem::get_basic...), I can see correct status, only in the code, only immediatly after create item, but if I get this item in the another code (just PodioItem::get_basic...) I will see default value, so code don't change status, looks like I just see some cache.
If I create item on the one script:
$fields = new PodioItemFieldCollection([
new PodioCategoryItemField(['external_id'=>'status', 'values'=>13]),
]);
$item = new PodioItem([
'app' => new PodioApp($app_id),
'fields' => $fields
]);
$item->save();
Then, in the another script update field, it will be change:
$get_item = PodioItem::get_basic('639637317');
$get_item->fields['status']->values = ['id'=>13];
$get_item->save();
Update - debug information:
Get log by test code -
PodioItem::create($app_id, ['fields' => ['status'=>[13], 'category'=>[3], 'contract-type'=>[4]]]);
(simple variant for creating an item, have the same problems like new PodioItem... )
All fields have category type, but:
status - have inline show type - don't chnages
category - have dropdown show type - Is changing
contract-type - have dropdown show type - Is changing
Log:
2017-07-08 11:07:22 200 POST /item/app/12152727/
2017-07-08 11:07:22 Request body: {"fields":{"status":[8],"category":[3],"contract-type":[4]}}
2017-07-08 11:07:22 Reponse: {
"presence": {
"ref_type": "item",
"ref_id": 641331142,
"user_id": 4194774,
"signature": "c165b85090e6ad28e74ae4baf93ee56113f88bc9"
},
"app": {
"status": "active",
"sharefile_vault_url": null,
"name": "Projects",
"default_view_id": null,
"url_add": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects\/items\/new",
"icon_id": 378,
"link_add": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects\/items\/new",
"app_id": 12152727,
"current_revision": 141,
"item_name": "Project",
"link": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects",
"url": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects",
"url_label": "projects",
"config": {
"item_name": "Project",
"icon_id": 378,
"type": "standard",
"name": "Projects",
"icon": "378.png"
},
"space_id": 3466816,
"icon": "378.png"
},
"created_on": "2017-07-10 15:31:16",
"last_event_on": "2017-07-10 15:31:16",
"linked_account_data": null,
"sharefile_vault_folder_id": null,
"app_item_id_formatted": "3988",
"recurrence": null,
"title": "ACSC",
"participants": {},
"created_by": {
"user_id": 4194774,
"name": "Anton Mikhailov",
"url": "https:\/\/podio.com\/users\/4194774",
"type": "user",
"image": null,
"avatar_type": "file",
"avatar": null,
"id": 4194774,
"avatar_id": null,
"last_seen_on": "2017-07-10 15:31:15"
},
"priority": 641331142.0,
"created_via": {
"url": null,
"auth_client_id": 25162,
"display": true,
"name": "importer",
"id": 25162
},
"subscribed_count": 1,
"reminder": null,
"ref": null,
"revision": 0,
"app_item_id": 3988,
"link": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects\/items\/3988",
"item_id": 641331142,
"sharefile_vault_url": null,
"rights": ["subscribe", "grant", "add_conversation", "rate", "update", "delete", "add_file", "grant_view", "view", "comment", "add_task"],
"fields": [{
"status": "active",
"type": "category",
"field_id": 93352415,
"label": "Division",
"values": [{
"value": {
"status": "active",
"text": "ACSC",
"id": 3,
"color": "D2E4EB"
}
}],
"config": {
"default_value": null,
"unique": false,
"description": null,
"hidden_create_view_edit": false,
"required": true,
"mapping": null,
"label": "Division",
"visible": true,
"delta": 5,
"hidden": false,
"settings": {
"multiple": false,
"options": [{
"status": "active",
"text": "ACSE",
"id": 1,
"color": "DCEBD8"
}, {
"status": "active",
"text": "ACSB",
"id": 2,
"color": "F7F0C5"
}, {
"status": "active",
"text": "ACSC",
"id": 3,
"color": "D2E4EB"
}],
"display": "dropdown"
}
},
"external_id": "category"
}, {
"status": "active",
"type": "category",
"field_id": 148215928,
"label": "Contract Type",
"values": [{
"value": {
"status": "active",
"text": "No Contract",
"id": 4,
"color": "DDDDDD"
}
}],
"config": {
"default_value": null,
"unique": false,
"description": null,
"hidden_create_view_edit": false,
"required": true,
"mapping": null,
"label": "Contract Type",
"visible": true,
"delta": 7,
"hidden": false,
"settings": {
"multiple": false,
"options": [{
"status": "active",
"text": "PO \/ Purchase \/ T&M",
"id": 1,
"color": "FFD5C2"
}, {
"status": "active",
"text": "Original Contract",
"id": 2,
"color": "D2E4EB"
}, {
"status": "active",
"text": "Service Rider",
"id": 3,
"color": "DCEBD8"
}, {
"status": "active",
"text": "No Contract",
"id": 4,
"color": "DDDDDD"
}],
"display": "dropdown"
}
},
"external_id": "contract-type"
}, {
"status": "active",
"type": "category",
"field_id": 93034840,
"label": "Instal Status",
"values": [{
"value": {
"status": "active",
"text": "Closed",
"id": 13,
"color": "E1D8ED"
}
}],
"config": {
"default_value": null,
"unique": false,
"description": null,
"hidden_create_view_edit": false,
"required": true,
"mapping": null,
"label": "Instal Status",
"visible": true,
"delta": 13,
"hidden": false,
"settings": {
"multiple": false,
"options": [{
"status": "deleted",
"text": "To Be Reviewed",
"id": 2,
"color": "F7F0C5"
}, {
"status": "deleted",
"text": "ACS Accounting Review",
"id": 5,
"color": "FFD5C2"
}, {
"status": "deleted",
"text": "Ignite Setup",
"id": 10,
"color": "DCEBD8"
}, {
"status": "active",
"text": "To Be Scheduled",
"id": 8,
"color": "D2E4EB"
}, {
"status": "active",
"text": "In Progress",
"id": 6,
"color": "DCEBD8"
}, {
"status": "active",
"text": "Warranty",
"id": 11,
"color": "F7F0C5"
}, {
"status": "active",
"text": "Complete",
"id": 3,
"color": "D1F3EC"
}, {
"status": "deleted",
"text": "Closed",
"id": 7,
"color": "DDDDDD"
}, {
"status": "active",
"text": "Cancelled",
"id": 9,
"color": "DDDDDD"
}, {
"status": "deleted",
"text": "VA in Progress",
"id": 4,
"color": "E1D8ED"
}, {
"status": "deleted",
"text": "Submitted",
"id": 1,
"color": "F7F0C5"
}, {
"status": "active",
"text": "On Hold",
"id": 12,
"color": "F7D1D0"
}, {
"status": "active",
"text": "Closed",
"id": 13,
"color": "E1D8ED"
}],
"display": "inline"
}
},
"external_id": "status"
}],
"initial_revision": {
"item_revision_id": 1664054437,
"created_via": {
"url": null,
"auth_client_id": 25162,
"display": true,
"name": "importer",
"id": 25162
},
"created_by": {
"user_id": 4194774,
"name": "Anton Mikhailov",
"url": "https:\/\/podio.com\/users\/4194774",
"type": "user",
"image": null,
"avatar_type": "file",
"avatar": null,
"id": 4194774,
"avatar_id": null,
"last_seen_on": "2017-07-10 15:31:15"
},
"created_on": "2017-07-10 15:31:16",
"user": {
"user_id": 4194774,
"name": "Anton Mikhailov",
"url": "https:\/\/podio.com\/users\/4194774",
"type": "user",
"image": null,
"avatar_type": "file",
"avatar": null,
"id": 4194774,
"avatar_id": null,
"last_seen_on": "2017-07-10 15:31:15"
},
"type": "creation",
"revision": 0
},
"current_revision": {
"item_revision_id": 1664054437,
"created_via": {
"url": null,
"auth_client_id": 25162,
"display": true,
"name": "importer",
"id": 25162
},
"created_by": {
"user_id": 4194774,
"name": "Anton Mikhailov",
"url": "https:\/\/podio.com\/users\/4194774",
"type": "user",
"image": null,
"avatar_type": "file",
"avatar": null,
"id": 4194774,
"avatar_id": null,
"last_seen_on": "2017-07-10 15:31:15"
},
"created_on": "2017-07-10 15:31:16",
"user": {
"user_id": 4194774,
"name": "Anton Mikhailov",
"url": "https:\/\/podio.com\/users\/4194774",
"type": "user",
"image": null,
"avatar_type": "file",
"avatar": null,
"id": 4194774,
"avatar_id": null,
"last_seen_on": "2017-07-10 15:31:15"
},
"type": "creation",
"revision": 0
},
"linked_account_id": null,
"push": {
"timestamp": 1499700676,
"expires_in": 21600,
"channel": "\/item\/641331142",
"signature": "b8a816ff367da6bc730071c875ca3fdca2d2c344"
},
"external_id": null
}
Have you tried http://podio.github.io/podio-php/fields/#category-field ?
Setting values
Set a single value by using the option_id. You can also
add a value with add_value()
$item = PodioItem::get_basic(123);
$field_id = 'category';
// Set value to a single option
$item->fields[$field_id]->values = 4; // option_id=4
// Add value to existing selection
$item->fields[$field_id]->add_value(4); // option_id=4
Use an array to set multiple values
$item = PodioItem::get_basic(123);
$field_id = 'category';
$item->fields[$field_id]->values = array(4,5,6); // option_ids: 4, 5 and 6
Creating item with value:
$fields = new PodioItemFieldCollection([
new PodioCategoryItemField(['external_id'=>'status', 'values'=>array(13)]),
]);
$item = new PodioItem([
'app' => new PodioApp($app_id),
'fields' => $fields
]);
$item->save();

Subscribed topics

In my forum I'm showing all topics. It looks like this:
So a user can subscribe by clicking on the red hearth.
I'm loading the topics with this json:
{
"forum": {
"id": 1,
"slug": "test",
"name": "test",
"description": "test",
"created_at": null,
"updated_at": null
},
"topics": {
"total": 6,
"per_page": 5,
"current_page": 1,
"last_page": 2,
"next_page_url": "http://forum.dev/api/forum/test?page=2",
"prev_page_url": null,
"from": 1,
"to": 5,
"data": [
{
"id": 1,
"slug": "1",
"name": "1",
"description": "1",
"forum_id": 1,
"created_at": null,
"updated_at": null
},
{
"id": 2,
"slug": "2",
"name": "1",
"description": "1\t",
"forum_id": 1,
"created_at": null,
"updated_at": null
},
{
"id": 3,
"slug": "1",
"name": "1",
"description": "1\t",
"forum_id": 1,
"created_at": null,
"updated_at": null
},
{
"id": 4,
"slug": "1",
"name": "1",
"description": "1",
"forum_id": 1,
"created_at": null,
"updated_at": null
},
{
"id": 5,
"slug": "1",
"name": "1",
"description": "1",
"forum_id": 1,
"created_at": null,
"updated_at": null
}
]
}
}
I'm returning that ^ like this:
$forum->topics()->orderBy('created_at', 'DESC')->paginate(5);
So how do I get a subscribe value on every topic object?
So like this:
"data": [
{
"id": 1,
"slug": "1",
"name": "1",
"description": "1",
"forum_id": 1,
"created_at": null,
"updated_at": null,
"subscribed": true
},
I already made this on my topic model:
/**
* #return mixed
*/
public function subscriptions()
{
return Topic::subscribedBy(Auth::user())->get();
}
And it's working. But how do I send that ^ with every topic.
You can add an attribute (which is not present in the database) by creating an accessor.
public function getSubscriptionsAttribute()
{
return Topic::subscribedBy(Auth::user())->get();
}
and then adding it to the $append property.
protected $appends = ['subscriptions'];
If you're using the $visible whitelist you might have to add it to that property too.
Source (Its all the way in the bottom.)

Categories