How to display record count in laravel? - mysql

this is my controller query:
$orderStatistics = OrderHeader::orderBy('order_status')
->select(DB::raw('order_status,count(*) as count'))
->groupBy('order_status')
->get();
and this returns a response as this:
"data": [
{
"order_status": "APR",
"count": 2
},
{
"order_status": "CNCL",
"count": 4
},
{
"order_status": "NTE",
"count": 3
},
{
"order_status": "PND",
"count": 2
},
{
"order_status": "SHP",
"count": 1
}
]
how can I return the relevant order_status and it's count for example as this:
APR : 2

You can use transform function on your collection:
$result = $result->transform(function($re){
return //your changes on an object ($re)
})
If you want make an array for JsonResponse:
$data=[];
foreach($results as $re){
$data[$re->order_status]=$re->count;
}
return response()->json($data);

you can try this way to format data like APR : 2 this ..
$orderStatistics = OrderHeader::orderBy('order_status')
->select(DB::raw('order_status,count(*) as count'))
->groupBy('order_status')
->get();
$orderStatistics = $orderStatistics->map(function($item){
return [
$item->order_status => $item->count,
];
});

$numb = 0;
$newOrderStatus=[];
foreach($orderStatistics as $orderStatistic){
array_push($newOrderStatus, $orderStatistic->data[$numb]->order_status.':'.$orderStatistic->data[$numb]->count;
$numb++
}
echo $newOrderStatus[0];// your example but you just return $newOrderStatus
return response()->json($newOrderStatus);
This is what i would think of fast if you want to echo it to a view as array object you just parse return response()->json($newOrderStatus) But as you receive it javascript will see it as a string so you have to parseJson(receiveddata);

Related

How to create object from arrays of row in laravel Elequent

Here I want to make the array inside "property" to an object where the key of the object will be the value of 'key_name' column of product_property table
[{
"sort_order": 1,
"name": "Samosas",
"visible": 1,
"description": null,
"property": [
{
"product_uuid": "95be9cf4-7121-492b-8725-762e6353ac51",
"key_name": "categories",
"key_value": "Starter"
},
{
"product_uuid": "95be9cf4-7121-492b-8725-762e6353ac51",
"key_name": "print_order",
"key_value": "1"
}
]
}]
This is what I want
[{
"sort_order": 1,
"name": "Samosas",
"visible": 1,
"description": null,
"property": {
"categories": "Starter",
"print_order": "1"
}
}]
I tried with Product::with('property')->get() and it results the first array.
Is there any Eloquent way to do that or raw sql or Query Builder?
Looping throw the result and make that object is possible but here i want something from SQL end
$products = Product::with('property')->get();
foreach ($products as $product) {
$array = [];
foreach ($product->property as $property) {
$array[$property['key_name']] = $property['key_value'];
}
$product->properties = $array;
}
This looping giving me the results but its from php end
public function property(){
return $this->hasMany(ProductProperty::class, 'product_uuid', 'uuid');
}
The Product model
Product table
"sort_order",
"name",
"visible",
"description",
Product Property table
"product_uuid",
"key_name",
"key_value"
Thanks in advance
$products = Product::with('property')->get();
foreach ($products as $product) {
$array = [];
foreach ($product->property as $property) {
$array[$property['key_name']] = $property['key_value'];
}
$product->properties = (object) $array;
}
Add object. It will convert this to a std object.

how to group result with json key name in laravel

user table
id name age
1 TuTu 3
2 SuSu 4
3 YuYu 4
4 MoMo 4
I want to output json like this.
[
{
"age": 3,
"user": [
{
"id": 2,
"name": "TuTu"
}
]
},
{
"age": 4,
"user": [
{
"id": 2,
"name": "SuSu"
},
{
"id": 3,
"name": "YuYu"
},
{
"id": 4,
"name": "MoMo"
}
]
}
]
User::get()->groupBy("age") not working expected.
How could add json key age and user like above format in laravel?
The answer gives you the desired output, however consider using an API Resource for JSON Response.
$response = [];
User::get()->groupBy('age')->each(function ($item, $key) use (&$response) {
$temp = [];
$temp['age'] = $key;
$temp['user'] = $item->transform(function ($i, $k) {
unset($i['age']);
return $i;
})->all();
$response[] = $temp;
});
var_dump($response); // Your Output JSON

check for duplicate date from data and assign to new one json

i have a json which contain duplicate date , i want to merge duplicate date into single json object.
Data:
[
{"date":"2017-06-26","mac":"66"},
{"date":"2017-06-26","window":"400"},
{"date":"2017-07-03","mac":"19"},
{"date":"2017-07-03","window":"12"}
]
output should be:
[
{"date":"2017-06-26","mac":"66","window":"400"},
{"date":"2017-07-03","mac":"19","window":"12"}
]
Here a javascript function that does that, you can apply JSON.stringify(...) to the output after passing your array and obtain the new json.
(( a ) => {
// used to check for already inserted dates
let withoutDupes = { };
if(Array.isArray(a)) {
a.forEach( (item) => {
// assuming item has a "date" property inside
if(withoutDupes[item.date]) {
withoutDupes[item.date] = Object.assign( item, withoutDupes[item.date] );
} else {
withoutDupes[item.date] = item;
}
} );
}
return Object.values( withoutDupes );
})( a )
You can try using jq command line parser and its group_by function:
jq '[group_by(.date)|.[]|add]' file
[
{
"date": "2017-06-26",
"mac": "66",
"window": "400"
},
{
"date": "2017-07-03",
"mac": "19",
"window": "12"
}
]

Want to remove Unexpected object like "headers","original","exception" from Laravel JSON output

I am getting JSON response like this. But I want to remove "headers", "original" and "exception".
{
"headers": {},
"original": [
{
"id": 271,
"name": "TestController",
"parent_id": null
}
],
"exception": null
}
Output expected:
{
"data": {
"id": 271,
"name": "TestController",
"parent_id": null
},
"errors": [],
"success": true,
"status_code": 200
}
You are returning a response()->json() inside another response()->json() something along the way:
response()->json(response()->json($data,200),200)
or more like:
$data = [
"id"=> 271,
"name"=> "TestController",
"parent_id"=> null
];
$response = response()->json($data,200);
return response()->json($response ,200);
You may not have notice it because of a function returning the first response()->json() into the second one
You can use this
$json='{
"headers": {},
"original": [
{
"id": 271,
"name": "TestController",
"parent_id": null
}
],
"exception": null
}';
$arr=json_decode($json);
$data=$arr->original[0];
$new_json=array();
$new_json['data']=$data;
$new_json['errors']=[];
$new_json['success']=true;
$new_json['status_code']=200;
$new_json=json_encode($new_json);
You may have doubled the data json return with response()->json()
you can use array only
return ["data"=> [
"id"=> 271,
"name"=> "TestController",
"parent_id"=> null
],
"errors"=> [],
"success"=> true,
"status_code"=> 200
];
In my case this problem solved with this solution:
You can use:
return json_decode(json_encode($ResponseData), true);
And return response
This is what I did, and it worked for me:
just call the original object after getting your response like this:
public function user_object(){
return $this->me()->original;
}
This is the me() function that returns user details
public function me()
{
return response()->json(auth('users')->user()->only(['id','name','email','status','phonenumber','type']));
}
This is my response from post man:
{
"success": true,
"user": {
"id": 29,
"name": "test6",
"email": "test6#gmail.com",
"status": 1,
"phonenumber": "413678675",
"type": "user"
},
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6ODAwMFwvYXBpXC9hdXRoXC9yZWdpc3RlciIsImlhdCI6MTU5OTQ3MDc3OCwiZXhwIjoxNTk5NDc0Mzc4LCJuYmYiOjE1OTk0NzA3NzgsImp0aSI6InFyUWEyTVNLVzR4a2o0ZVgiLCJzdWIiOjI5LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.SMHgYkz4B4BSn-fvUqJGfsgqHc_r0kMDqK1-y9-wLZI",
"expires_in": 3600
}
The issue is triggered because you are returning nested responses somewhere in your code.
Here is a simple code that demonstrates the issue and the fix.
// A normal function that you think it returns an array
// but instead, it is returning a response object!
public function get_data(){
//ISSUE
return response([1, 2, 3]); // <- this will trigger the issue becuase
// it returns the data as a response not an array
//FIX
return [1, 2, 3]; // <- this will work as intended
// bacause the data is returned as a normal array
}
public function get_all_data(){
$first_array = [1, 2];
$second_array = [2, 3];
$third_array = get_data(); // <- here is the call to the function
// that should return an array
//Return the JSON response
return response([first_array, second_array, third_array]);
}

Access nested JSON object in AngularJS controller

I am new to AngularJS and trying to create a $scope for tracks for later usage
data.json (sample):
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
Controller
app.controller('lyricsCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(result) {
$scope.albums = result.data;
$scope.tracks = result.data.tracks;
console.log($scope.tracks); //Undefined...
});
});
Why is $scope.tracks undefined?
If your json file is as is:
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
We have a response of:
data: Array[1]
0: Object
album: "Album name"
tracks: Array[2]
Since data is returned as an array you would handle like any other javascript array and access by index, so you could do a loop or if you know only 1 result is going to be returned you could use the zero index:
$http.get('data.json').then(function(result) {
console.log(result);
// Assign variables
$scope.album = result.data[0].album;
$scope.tracks = result.data[0].tracks;
for (var i = 0, l = $scope.tracks.length; i < l; i++) {
console.log($scope.tracks[i].title);
}
});
result.data is an array,So you must have to use index to access its child like:-
$scope.tracks = result.data[0].tracks;
It should be result.data[0].tracks as data is an array
$scope.tracks = result.data[0].tracks;