I have a single array of data, I want to add a key and it's value in same array . Here in addedPost I want to add key favouritePost and it's value is $favouritePost after product key. How can i do this ?
Here is my query:
$addedPost = Post::with(['product','postattribute.attribute.category','user.userDetails'])
->whereId($postData['post_id'])
->first();
$favouritePost = PostFavourite::isAlreadyAdded($postData['post_id'], Auth::id());
return [
'status_code' => $status_code,
'message' => $message,
'PostDetails' => $addedPost
];
What I get in response :
{
"PostDetails": {
"id": 289,
"user_id": 12,
"product_id": 2,
"demand_or_supply": "Demand",
"description": "edited1",
"status": "Expired",
"created_at": "2018-06-22 07:35:27",
"updated_at": "2018-07-05 06:42:56",
"product": {
"id": 2,
"title": "Diamond",
"icon": null,
"status": "Active"
}
}
}
EXPECTED RESULT:
{
"PostDetails": {
"id": 289,
"user_id": 12,
"product_id": 2,
"demand_or_supply": "Demand",
"description": "edited1",
"status": "Expired",
"created_at": "2018-06-22 07:35:27",
"updated_at": "2018-07-05 06:42:56",
"product": {
"id": 2,
"title": "Diamond",
"icon": null,
"status": "Active"
},
"favouritepost": {
"id": 8,
"post_id": 289,
"user_id": 12
}
}
}
First: Your $addedPost is not an array but a Eloquent Collection. There are multiple possibilites to do this. The easiest one is to union an Array with the Collection.
$union = $addedPost->union($favouritePost->toArray());
For every other solution please take a look at the Laravel Documentation. It's pretty easy to understand.
https://laravel.com/docs/5.6/collections
Edit: Though I missed the ->first() inside the question just use the solution already mentioned. ->first() returns a StdClass Object, so you can handle it like it:
$addedPost->favouritepost = $favouritePost;
That property favouritePost is added to $addedPost object in that case. There's no need for any method call again.
first you store all the values which you are returning in one associative array then use array_push() to add new key/value in that array.After all you just return that array.
Assuming that $addedPost is a laravel collection you can simply do:
$addedPost = Post::with(['product','postattribute.attribute.category','user.userDetails'])
->whereId($postData['post_id'])
->first();
$favouritePost = PostFavourite::isAlreadyAdded($postData['post_id'], Auth::id());
$addedPost->put('favouritepost', $favouritePost);
return [
'status_code' => $status_code,
'message' => $message,
'PostDetails' => $addedPost
];
for adding key value in object
$object->new_key="value";
Related
I have in the MySql table column that called "more_data" and its contain json array:
[{
"notes": null,
"status": 0,
"type_id": 1,
"start_id": 1001
},
{
"notes": null,
"status": 1,
"type_id": 2,
},
{
"notes": null,
"status": 1,
"type_id": 3,
},
{
"notes": null,
"status": 1,
"type_id": 4,
}]
I need to get only this JSON from the query but just where status is 1.
So I don't want to get the first element.
There is way to do that?
Thanks.
If the "more_data" column is a type of JSON, You can get the values by whereJsonContains() function. https://laravel.com/docs/5.8/queries#json-where-clauses
Otherwise, you have to decode the JSON and filter the array.
Try this
$a=YourModel::find($id);
$b=$a->more_data;
$data=[];
foreach($b as $c)
{
if(($c['status'])==1)
{
$data[]=$c;
}
}
dd($data);
This question already has answers here:
How to remove index number from laravel eloquent unique
(2 answers)
Closed 3 years ago.
$message = Message::where('agent_id', $agent->id)->orderBy('id', 'DESC')->get();
I used unique() on collection and now I got this result:
{
"0": {
"id": 1,
"post_id": 3,
"agent_id": 1,
"user_id": 1,
"message": "hello",
"status": 0
},
"3": {
"id": 4,
"post_id": 5,
"agent_id": 1,
"user_id": 2,
"message": "hi hello",
"status": 0
}
}
But I want to remove key index, I mean 0 and 3, desire output is:
[
{
"id": 1,
"post_id": 3,
"agent_id": 1,
"user_id": 1,
"message": "hello",
"status": 0
},
{
"id": 4,
"post_id": 5,
"agent_id": 1,
"user_id": 2,
"message": "hi hello",
"status": 0
}
]
I tried:
$message->unique('user_id')->toArray();
But not working. any idea?
I using Laravel.
Use the values method of the Collection, similar to array_values:
$new = $message->values();
Assuming $message is the Collection holding the result of the unique call.
Laravel 6.x Docs - Collections - Available Methods - values
Try using group by groupBy('user_id')
$message = Message::where('agent_id', $agent->id)
->groupBy('user_id')
->orderBy('id', 'DESC')
->get();
I have this data in method of controller as you see I deleted some keys in method:
$foods = Food::get()->map(function($value){
return collect($value->toArray())->except('pivot', 'deleted_at', 'created_at', 'updated_at');
});
return HttpHelpers::sendJsonData($foods, 200);
and the api response returns this:
{
"success": true,
"data": [
{
"id": 1,
"title": "food1",
"default_price": 2353465456,
"main_meal": 1,
"labels": [
{
"id": 1,
"title": "type1",
"type": "food",
"created_at": "2018-08-23 03:55:33",
"updated_at": "2018-08-23 03:55:33",
"pivot": {
"labelable_id": 1,
"label_id": 1,
"labelable_type": "App\\Models\\Panel\\Food"
}
}
]
},
{
"id": 2,
"title": "food2",
"default_price": 1000,
"main_meal": 0,
"labels": [
{
"id": 1,
"title": "type2",
"type": "food",
"created_at": "2018-08-23 03:55:33",
"updated_at": "2018-08-23 03:55:33",
"pivot": {
"labelable_id": 2,
"label_id": 1,
"labelable_type": "App\\Models\\Panel\\Food"
}
}
]
}
]
}
now my problem is that I do not want to return some keys, like labalable_id and labelable_type in pivot and created_at in labels, please offer me the best way
You can use the makeHidden method for hiding data to JSON. Haven't tried this code but, i think it should work.
https://laravel.com/docs/5.6/eloquent-serialization#hiding-attributes-from-json
$foods = Food::get()->map(function($value){
foreach($value->labels as $label){
$label = $label->makeHidden(['created_at']);
$label->pivot = $label->pivot->makeHidden(['labelable_id', 'labelable_type']);
}
return collect($value->toArray())->except('pivot', 'deleted_at', 'created_at', 'updated_at');
});
If the data response is coming through the stored procedure then in that case you need to store the Pivot table data in a temporary table and select the required keys that you require and display it through API in json.
I get data from database using this query
$cats = Category::with(['cat_trans' => function($q) use($lang){
$q->where('lang_code', $lang);
}])->with(['cat_prod' => function($query) use ($lang,$currency){
$query->with(['pro_trans' => function ($q) use ($lang){
$q->where('lang_code', $lang);
}]);
////////////
$query->with(['pro_price' => function ($q) use ($currency){
$q->with('currency_code')->where('cur_code', $currency);
}]);
///////////
}])->whereHas('account_type', function($qr) use ($account_type){
$qr->where('account_type_id', $account_type);
})->get();
I'm trying to remove the empty objects from the result, when I tried this I got the following response
{
"1": {
"id": 1,
"parent_id": null,
"order": 1,
"name": "Moblie",
"slug": "mobile-1",
"created_at": "2018-07-08 09:41:08",
"updated_at": "2018-07-08 10:30:17",
"cat_trans": [
{
"id": 1,
"category_id": 1,
"field": "title",
"value": "Mobile",
"lang_code": "en",
"created_at": "2018-07-08 09:51:59",
"updated_at": "2018-07-08 09:51:59"
},
{
"id": 2,
"category_id": 1,
"field": "desc",
"value": "smart",
"lang_code": "en",
"created_at": "2018-07-08 09:52:41",
"updated_at": "2018-07-08 09:52:41"
},
{
"id": 12,
"category_id": 1,
"field": "slug",
"value": "mobile-1",
"lang_code": "en",
"created_at": null,
"updated_at": null
}
],
}
}
I want to remove the key "1" from all the responses.
I used unset to get this value using this code
foreach ($cats as $k) {
if (count($k->cat_prod) == 0) {
unset($cats[$va]);
}
$va++;
}
Then I tried using array_values but it displays that I can just use array_values on an array not an object.
You can remove key "1" by simply doing
array_values((array)$cats)
You were receiving error for this function like "Can Only be used on array" was due to Laravel Query returns object , so you just need to do type conversion on it.
$cats->toArray() if u need either to convert object to array or convert with some specific conditions
Your output looks like JSON so you can do this to eliminate the 1:
json_encode( $cats->{1} );
You can use laravel simple method mapWithKeys()
$cats = $cats->mapWithKeys(function ($item) {
return $item > 2;
});
$keyed->all();
[{
"forms": [{
"id": "52b55960-023e-11e7-9140-f3c1d163524b",
"title": "Default Form",
"update_history": [{
"version": "1",
"updated_at": "2016-12-10 12:12:10"
}, {
"version": "2",
"updated_at": "2017-01-01 05:17:19"
}, {
"version": "3",
"updated_at": "2017-02-07 03:22:39"
}, {
"version": "4",
"updated_at": "2017-03-03 02:28:56"
}, {
"version": "5",
"updated_at": "2017-01-11 07:01:22"
}]
}]
}]
I have above Json stored in Dynamo-DB table. forms object is parent object. I have stored form updated detail version and updated_at in update_history nested object. I want updated_at of version of 2. Please suggest me, what is wrong in below query. I got empty result.
`$response = $client->scan([
'TableName' => 'TableName',
'ProjectionExpression' => 'Json.forms.update_history.updated_at',
'ExpressionAttributeValues' => [
':val1' => ['S' => '52b55960-023e-11e7-9140-f3c1d163524b'],
':val2' => ['S' => '2']
],
'FilterExpression' => 'id = :val1 and Json.forms.update_history.version = :val2',
]);`
Please refer the DocumentPath example in the below link and try to use deference operator.
For a nested attribute, you construct the document path using
dereference operators.
If you don't know the deference operator (i.e. index), you can't filter the data as you have tried.
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html#DocumentPaths
Example:-
Accessing List Elements:-
MyList[0]
AnotherList[12]
ThisList[5][11]
Accessing Map Elements:-
MyMap.nestedField
MyMap.nestedField.deeplyNestedField
You have the combination of both Map and List, you need to FilterExpression accordingly.