Obtain KEY Value Array in variable PHP - php

Hi I have this array code and I need to get: user_id": 4
I just need to get the value 4 from user_id
I have this code but it doesn't work
$myvar = $request['order'][0]['user_id'];
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NpdGUudGVzdC9wdWJsaWMvYXBpL2xvZ2luIiwiaWF0IjoxNjIzODExMTE1LCJuYmYiOjE2MjM4MTExMTUsImp0aSI6Ind2bExlTlJHdkdpU2xmVUYiLCJzdWIiOjIsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.-Q56kEsHZgVEtaMzSS9Ub11imYjWjFbJMAug3Wx7WTg",
"user": {
"success": true,
"data": {
"id": 2,
"auth_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NpdGUudGVzdC9wdWJsaWMvYXBpL2xvZ2luIiwiaWF0IjoxNjIzODExMTE1LCJuYmYiOjE2MjM4MTExMTUsImp0aSI6Ind2bExlTlJHdkdpU2xmVUYiLCJzdWIiOjIsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.-Q56kEsHZgVEtaMzSS9Ub11imYjWjFbJMAug3Wx7WTg",
"name": "Leo",
"email": "ventas#nikostore.net",
"phone": "+51943363373",
"default_address_id": 3,
"default_address": {
"address": "mi dirección",
"house": null,
"latitude": "-1.327080900000001",
"longitude": "-10.6348053",
"tag": null
},
"delivery_pin": "51972",
"wallet_balance": 0,
"avatar": null,
"tax_number": null
},
"running_order": null,
"delivery_details": null
},
"order": [{
"selectedaddons": [{
"addon_category_name": "Comida Marina Ingredientes",
"addon_id": "2",
"addon_name": "Cangrejo Adicional",
"price": "32.00"
}],
"id": 5,
"restaurant_id": 12,
"item_category_id": 2,
"name": "Producto 1 Loquillo",
"price": "423.00",
"old_price": "0.00",
"image": "https://localhost/phpmyadmin/themes/pmahomme/img/logo_left.png",
"is_recommended": 1,
"is_popular": 1,
"is_new": 1,
"desc": "<p>321312</p>",
"placeholder_image": null,
"is_active": 1,
"is_veg": null,
"order_column": null,
"addon_categories": [{
"id": 2,
"name": "Comida Marina Ingredientes",
"type": "SINGLE",
"user_id": 4,
"created_at": "2021-06-10 20:18:37",
"updated_at": "2021-06-10 20:39:18",
"description": null,
"pivot": {
"item_id": 5,
"addon_category_id": 2
},
"addons": [{
"id": 2,
"name": "Cangrejo Adicional",
"price": "32.00",
"addon_category_id": 2,
"user_id": 4,
"created_at": "2021-06-10 20:20:30",
"updated_at": "2021-06-10 20:38:51",
"is_active": 1
}, {
"id": 3,
"name": "Pene",
"price": "95.00",
"addon_category_id": 2,
"user_id": 4,
"created_at": "2021-06-10 23:52:53",
"updated_at": "2021-06-10 23:52:53",
"is_active": 1
}]
}],
"quantity": 1
}],
"coupon": null,
"location": {
"lat": "-5.187080900000001",
"lng": "-80.6348053",
"address": "midreccion",
"house": null,
"tag": null
},
"order_comment": null,
"total": {
"productQuantity": 1,
"totalPrice": 455
},
"method": "COD",
"payment_token": "",
"delivery_type": 1,
"partial_wallet": false,
"dis": 0,
"pending_payment": false,
"tipAmount": null
}

Working from the JSON string you posted here, you need to decode it first with json_decode(). Assuming no flags are set, this will decode to a mix of objects and arrays as represented in the JSON string.
$str = '{"token": "ey...WTg",
"user": {
...
}
}'; //The JSON string you posted in the question
$request = json_decode($str);
From there the path to the user_id is:
$request->order[0]->addon_categories[0]->user_id // 4

Use foreach loop.
Assuming that you have stored array in variable $array.
Code :
foreach($array as $arr)
{
if($arr['user_id'] == 4)
{
$user = $arr;
}
}
You will get the entire object which has user_id 4, you can get related column by
$user_id = $user['user_id];
Hope this will be useful.

Related

How can loop & get values of unlimited parent-child & sub-child tree data in laravel

I have data like parent-child with unlimited levels of sub-child & sub-child data in the database which you can see below like a binary tree with nodes that have multiple children and these children can have unlimited sub-child.
Please give me a solution or suggestion how can show that. Thanks.
This is my database JSON data which I'm getting from the database...
Controller Code
$products = Product::where('project_id', $project_id )->whereNull('parent_id')->with('categories')->with('childProducts')->get();
Getting data from the above object this data want to save in the other way you can see below
{
"data": {
"products": [{
"id": 1,
"name": "ParentProduct",
"project_id": 1,
"parent_id": null,
"created_by": 1,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [{
"id": 6,
"product_id": 1,
"project_id": 1,
"name": "TopLevelCategory",
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00"
}],
"child_products": [{
"id": 2,
"name": "LevelOneProduct",
"project_id": null,
"parent_id": 1,
"created_by": null,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [{
"id": 1,
"product_id": 2,
"project_id": 1,
"name": "LevelOneProductCategory",
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00"
}],
"child_products": [{
"id": 3,
"name": "LevelOneProductChildFolder",
"project_id": null,
"parent_id": 2,
"created_by": null,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [{
"id": 2,
"product_id": 3,
"project_id": 1,
"name": "evelOneProductChildFolderCategory",
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00"
}],
"child_products": [{
"id": 4,
"name": "LevelOneProductSubChildFolder",
"project_id": null,
"parent_id": 3,
"created_by": null,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [{
"id": 3,
"product_id": 4,
"project_id": 1,
"name": "LevelOneProductSubChildFolderCategory",
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00"
}],
"child_products": []
}]
}]
},
{
"id": 5,
"name": "LeveTwoProduct",
"project_id": null,
"parent_id": 1,
"created_by": null,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [],
"child_products": [{
"id": 6,
"name": "LeveTwoProductFolder",
"project_id": null,
"parent_id": 5,
"created_by": null,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [{
"id": 4,
"product_id": 6,
"project_id": 1,
"name": "LeveTwoProductFolderCategory",
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00"
}],
"child_products": [{
"id": 7,
"name": "LeveTwoProductChildFolder",
"project_id": null,
"parent_id": 6,
"created_by": null,
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00",
"categories": [{
"id": 5,
"product_id": 7,
"project_id": 1,
"name": "LeveTwoProductChildFolderCategory",
"created_at": "2021-08-06 13:18:00",
"updated_at": "2021-08-06 13:18:00"
}],
"child_products": []
}]
}]
}
]
}]
}
}
I want to take this data to another JSON data which I have to give you an example as mentioned below I want to loop the above JSON data and want to make their need JSON with this data as like Dear Problem is that How can loop above data and can give to the other JSON keys you can see below. I want all data with loop and want to get all values and want equal all values to the keys as below
foreach ($products as $product) {
foreach ($product->categories as $singleCaegory) {
$singleCaegoryData = [
"name" => $singleCaegory->name,
"request" => [
'method' => $singleCaegory->type,
'body' => [
"mode" => "raw",
'raw' => $singleCaegory->raw_data
],
'url' => [
"raw" => $singleCaegory->url
],
],
];
}
}
I think you understand my problem. that I want to loop above data which I have already in the database and fetching from that. I only want to loop all data and equal to the needed keys. Thanks.
for saving Id's you only need:-parent Id, child_Id_count(count of the only direct child), total_child_count(count all children below).that's it by using these data and created date you can generate a tree view.

Laravel I can't retrieve requester data using with

I am using this package
https://github.com/renoki-co/befriended
My issue is trying to get all my friends posts with my post including user's data, but the problem is the requester data is null.
$user = $request->user();
$followersPost = UserPost::with(['user' => function ($query) use ($user) {
$query->filterFollowingsOf($user);
}])->latest()->get();
return $followersPost;
Response
[
{
"id": 35,
"post_body": "The Requster Post",
"location_id": "4b0da1acf964a520b94c23e3",
"location_title": "Apple Infinite Loop",
"location_icon": "https://ss3.4sqi.net/img/categories_v2/shops/technology_bg_44.png",
"location_coordinate": "{"latitude":37.33167558501772,"longitude":-122.030189037323,"latitudeDelta":0.001,"longitudeDelta":0.001}",
"location_vicinity": "Cupertino - 1 Infinite Loop",
"user_id": 1,
"viewer_ids": null,
"created_at": "2020-12-06T18:08:58.000000Z",
"updated_at": "2020-12-06T18:08:58.000000Z",
"images": [
],
"musics": [
],
"movies": [
],
"emojs": [
],
"user": null
},
{
"id": 34,
"post_body": "Test Post",
"location_id": "4b0da1acf964a520b94c23e3",
"location_title": "Apple Infinite Loop",
"location_icon": "https://ss3.4sqi.net/img/categories_v2/shops/technology_bg_44.png",
"location_coordinate": "{"latitude":37.33167558501772,"longitude":-122.030189037323,"latitudeDelta":0.001,"longitudeDelta":0.001}",
"location_vicinity": "Cupertino - 1 Infinite Loop",
"user_id": 2,
"viewer_ids": null,
"created_at": "2020-12-06T18:08:14.000000Z",
"updated_at": "2020-12-06T18:08:14.000000Z",
"images": [
],
"musics": [
],
"movies": [
],
"emojs": [
],
"user": {
"id": 2,
"_id": "dfa19aa6-510b-4aaf-8475-4386da9de3d0",
"name": "Saleh",
"username": "saleh",
"email": "saleh#gmail.com",
"email_verified_at": null,
"avatar": "http://backend.mf.sa/storage/avatars/1607128041.jpg",
"location": null,
"gender": "male",
"bio": null,
"birthday": null,
"phone": null,
"created_at": "2020-12-05T00:27:02.000000Z",
"updated_at": "2020-12-05T00:27:21.000000Z"
}
},
{
"id": 24,
"post_body": null,
"location_id": null,
"location_title": null,
"location_icon": null,
"location_coordinate": null,
"location_vicinity": null,
"user_id": 3,
"viewer_ids": null,
"created_at": "2020-12-06T01:53:18.000000Z",
"updated_at": "2020-12-06T01:53:18.000000Z",
"images": [
],
"musics": [
{
"id": 4,
"post_id": 24,
"song_name": "Confetti",
"song_preview": "https://cdns-preview-6.dzcdn.net/stream/c-6eb643a05083c023f874f13739fc7c87-3.mp3",
"song_picture": "https://api.deezer.com/album/183603832/image",
"song_artist": "Little Mix",
"created_at": "2020-12-06T01:53:18.000000Z",
"updated_at": "2020-12-06T01:53:18.000000Z"
}
],
"movies": [
],
"emojs": [
{
"id": 16,
"post_id": 24,
"user_id": 3,
"emojy": "015-smile-1",
"created_at": "2020-12-06T01:59:15.000000Z",
"updated_at": "2020-12-06T01:59:15.000000Z",
"user": {
"id": 3,
"_id": "af65864b-f18a-4609-91db-336acbce1486",
"name": "Ali",
"username": "ali2323",
"email": "ali#gmail.com",
"email_verified_at": null,
"avatar": null,
"location": null,
"gender": "male",
"bio": null,
"birthday": null,
"phone": null,
"created_at": "2020-12-05T04:05:50.000000Z",
"updated_at": "2020-12-05T04:05:50.000000Z"
}
},
{
"id": 17,
"post_id": 24,
"user_id": 1,
"emojy": "089-broken-heart",
"created_at": "2020-12-06T16:58:07.000000Z",
"updated_at": "2020-12-06T16:58:24.000000Z",
"user": {
"id": 1,
"_id": "737ba284-424d-4b0d-8a56-2e845603f2ba",
"name": "Mohammed",
"username": "mohammed",
"email": "h4ck3r.x0#gmail.com",
"email_verified_at": null,
"avatar": "http://backend.mf.sa/storage/avatars/1607128001.jpg",
"location": null,
"gender": "male",
"bio": null,
"birthday": null,
"phone": null,
"created_at": "2020-12-05T00:26:09.000000Z",
"updated_at": "2020-12-05T00:26:41.000000Z"
}
},
{
"id": 19,
"post_id": 24,
"user_id": 2,
"emojy": "021-sad",
"created_at": "2020-12-06T16:58:36.000000Z",
"updated_at": "2020-12-06T16:58:36.000000Z",
"user": {
"id": 2,
"_id": "dfa19aa6-510b-4aaf-8475-4386da9de3d0",
"name": "Saleh",
"username": "saleh",
"email": "saleh#gmail.com",
"email_verified_at": null,
"avatar": "http://backend.mf.sa/storage/avatars/1607128041.jpg",
"location": null,
"gender": "male",
"bio": null,
"birthday": null,
"phone": null,
"created_at": "2020-12-05T00:27:02.000000Z",
"updated_at": "2020-12-05T00:27:21.000000Z"
}
}
],
"user": {
"id": 3,
"_id": "af65864b-f18a-4609-91db-336acbce1486",
"name": "Ali",
"username": "ali2323",
"email": "ali#gmail.com",
"email_verified_at": null,
"avatar": null,
"location": null,
"gender": "male",
"bio": null,
"birthday": null,
"phone": null,
"created_at": "2020-12-05T04:05:50.000000Z",
"updated_at": "2020-12-05T04:05:50.000000Z"
}
}
]
As you can see the first object in the array dosen't include the user data.
So what should i do $query->filterFollowingsOf($user); to include my data?
I think the with callback is used for modifying the query that selects the user data. Instead, try using a whereHas method that filters the related users.
$user = $request->user();
$followersPost = UserPost
::with('user')
->whereHas('user', function ($query) use ($user) {
$query->filterFollowingsOf($user);
})
->latest()
->get();
return $followersPost;
I'd also recommend using paginate() instead of get() for performance when there could be a significant number of posts.
Edit:
To get either your friend's posts or your posts, try:
$followersPost = UserPost
::with('user')
->whereHas('user', function ($query) use ($user) {
$query->filterFollowingsOf($user);
})
->orWhere('user_id', $user->id)
->latest()
->get();

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

How can I hidden data in JSON if variable is empty

I got a some trouble in my Laravel application, in Search function, when I do search the result is
{
"data": [
{
"id": 2,
"user_id": 8,
"identity_number": "213918273",
"name": "Pekerja_2",
"gender_id": 1,
"date_of_birth": "1999-05-25",
"address": "Jalan Bandung Raya no 50",
"province_id": 32,
"city_id": 3273,
"district_id": 3273160,
"phone": "4232343432",
"image": null,
"created_at": "2018-01-11 10:59:54",
"updated_at": "2018-01-11 10:59:54",
"partner_id": null,
"skill": [
{
"id": 3,
"worker_id": 2,
"skill_id": 6,
"sub_skill_id": 18,
"created_at": "2018-01-15 13:06:48",
"updated_at": "2018-01-15 13:06:48",
"price": null,
"unit": null
}
]
},
{
"id": 3,
"user_id": 16,
"identity_number": "213918273",
"name": "Pekerja_3",
"gender_id": 1,
"date_of_birth": "1999-05-25",
"address": "Jalan Bandung Raya no 50",
"province_id": 32,
"city_id": 3273,
"district_id": 3273160,
"phone": "2345234234",
"image": null,
"created_at": "2018-01-15 13:06:48",
"updated_at": "2018-01-15 13:06:48",
"partner_id": null,
"skill": []
}
]
}
as you can see that "Skill" with id number 3 is empty, I want all in id number 3 is empty also.
My controller is :
$worker = Worker::with(['skill' => function($q) use ($request) {
$q->where('worker_skills.sub_skill_id', $request['sub_skill_id']);
}])->whereHas('skill');
And I want something like this :
{
"data": [
{
"id": 2,
"user_id": 8,
"identity_number": "213918273",
"name": "Pekerja_2",
"gender_id": 1,
"date_of_birth": "1999-05-25",
"address": "Jalan Bandung Raya no 50",
"province_id": 32,
"city_id": 3273,
"district_id": 3273160,
"phone": "2534234234",
"image": null,
"created_at": "2018-01-11 10:59:54",
"updated_at": "2018-01-11 10:59:54",
"partner_id": null,
"skill": [
{
"id": 3,
"worker_id": 2,
"skill_id": 6,
"sub_skill_id": 18,
"created_at": "2018-01-15 13:06:48",
"updated_at": "2018-01-15 13:06:48",
"price": null,
"unit": null
}
]
},
]
}
The point is, if "skill" variable is empty then data not show and vice versa.
Thankyou any help will appreciate, sorry for bad english
You can add a callback to your whereHas function with the same filter as the with function
$worker = Worker::with(['skill' => function($q) use ($request) {
$q->where('worker_skills.sub_skill_id', $request['sub_skill_id']);
}])
->whereHas('skill', function($q) use ($request) {
$q->where('worker_skills.sub_skill_id', $request['sub_skill_id']);
})
->get();
You can try this $worker = Worker:has('skill')->get();
Only worker that have at least one skill are contained in the collection

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