need to ask,
currently i'm using laravel and db query builder to create the function below.
Requirement is to get the query result without the bracket / object but with { }
Function is below :
$score = DB::table('m_player_scorecard')
->where('session_id', '=', $sessionID)
->orderBy('created_at', 'desc')
->get();
$scoreArr = json_decode(json_encode($score), true);
return response()
->json($scoreArr);
when i try to hit from postman :
[
{
"id": 153,
"session_id": "9e3bb8296fd195c66ced470ec50301385f6cd31a17012e26fd0099bdf821338c",
"round_order": 2,
"player_one_id": 1,
"score_one": 10,
"player_two_id": 2,
"score_two": 10,
"player_three_id": 3,
"score_three": 30,
"player_four_id": 4,
"score_four": 40,
"notes": null,
"created_at": "2020-06-06 18:15:27",
"updated_at": null
},
{
"id": 152,
"session_id": "9e3bb8296fd195c66ced470ec50301385f6cd31a17012e26fd0099bdf821338c",
"round_order": 1,
"player_one_id": 1,
"score_one": 10,
"player_two_id": 2,
"score_two": 20,
"player_three_id": 3,
"score_three": 30,
"player_four_id": 4,
"score_four": 40,
"notes": null,
"created_at": "2020-06-06 18:14:39",
"updated_at": null
}
]
I need to change the bracket [ ] to { }.
How to do that?
Thanks before
You have updated your question, so I updated my answer :
$remove = array("[", "]");
$replace = array("{", "}");
$newJson = str_replace($remov, $replace, $oldJson);
Related
I have a table name leave_requests like this
[leave request table][1]
[1]: https://i.stack.imgur.com/B7VvC.png
from above table I want to get total leaves between two time like (From 2021-12-02 to 2021-12-07) only when I have status "Approved", I have done this so far
LeaveRequest
::where("start_date", ">=", $request->from)
->where("end_date", "<=", $request->to)
->where("status", "approved")
->get()
as from above code I am matching two date conditions, this is the output:
{
"id": 31,
"code": "1o1545",
"organization_id": 1,
"employee_id": 7,
"leave_id": 1,
"start_date": "2021-12-03",
"end_date": "2021-12-06",
"reason": "sick",
"status": "approved",
"created_at": "2021-12-01 21:01:59",
"updated_at": "2021-12-01 21:02:14",
"leave_days": 4,
"is_archived": false,
"is_inactive": true,
"is_geofencing": false,
"is_tax_exempted": false,
"full_name": "",
"current_position": null
},
{
"id": 34,
"code": "mygm39",
"organization_id": 1,
"employee_id": 7,
"leave_id": 1,
"start_date": "2021-12-04",
"end_date": "2021-12-04",
"reason": "ljk",
"status": "approved",
"created_at": "2021-12-03 09:35:59",
"updated_at": "2021-12-03 09:35:59",
"leave_days": 1,
"is_archived": false,
"is_inactive": true,
"is_geofencing": false,
"is_tax_exempted": false,
"full_name": "",
"current_position": null
},
{
"id": 35,
"code": "m1e8zy",
"organization_id": 1,
"employee_id": 7,
"leave_id": 1,
"start_date": "2021-12-07",
"end_date": "2021-12-07",
"reason": "jj",
"status": "approved",
"created_at": "2021-12-03 09:36:43",
"updated_at": "2021-12-03 09:36:43",
"leave_days": 1,
"is_archived": false,
"is_inactive": true,
"is_geofencing": false,
"is_tax_exempted": false,
"full_name": "",
"current_position": null
}
The problem is that it will not give me rows where date is present like date is starting from (2021-12-02) but it didnot give me that record plus how to count leaves from leaves column. hope I am clear and please someone help me here I am new to laravel thanks.
Try this query:
LeaveRequest
::where("start_date", ">=", $request->from)
->where("end_date", "<=", $request->to)
->where("status", "approved")
->select('leave_id', \DB::raw('count(*) as total_leaves'))
->groupBy('leave_id')
->get();
I have finally found a solution to this below is code attached for someone in future:
use App\Models\LeaveRequest;
use Carbon\CarbonPeriod;
$total_leaves = 0;
LeaveRequest
::when($request->from && $request->to, function($query) use($request) {
$query
->whereDate("leave_requests.start_date", "<=", $request->to)
->whereDate("leave_requests.end_date", ">=", $request->from);
})
->when($request->from && !$request->to, function($query) use($request) {
$query
->whereDate("leave_requests.start_date", "<=", $request->from)
->whereDate("leave_requests.end_date", ">=", $request->from);
})
->where("leave_requests.status", "approved")
->get()
->map(function($leave_request) use(&$total_leaves, $request) {
// echo $leave_request->start_date . " " . $leave_request->end_date . "<br/>";
if(!$request->to && Carbon::parse($request->from)->betweenIncluded($leave_request->start_date, $leave_request->end_date)) {
$total_leaves++;
} else {
// echo $leave_request->start_date . " " . $leave_request->end_date . "<br/>";
$DB_periods = CarbonPeriod::create($leave_request->start_date, $leave_request->end_date);
$REQUEST_periods = CarbonPeriod::create($request->from, $request->to);
foreach ($DB_periods as $period1) {
// echo "DB-> " . $period1->format('Y-m-d') . "<br>";
foreach($REQUEST_periods as $period2) {
// echo "Request-> " . $period2->format('Y-m-d') . "<br>";
if($period1 == $period2) {
$total_leaves++;
}
}
}
}
});
return "Total Leaves: " . $total_leaves;
As I have told I am new to programming and make this solution after many hours of hardships so point is this code is lengthy and maybe not such good practice, so if any pro can minimize it thanks.
I would like to add an object into a existing json object :
My existing json object :
{
"id": 1,
"horaire_id": 1,
"json": "{"i": "idHoraire1-NumReservation1", "x": 3, "y": 2, "w":5, "h": 3, "j": 0}",
"num_reserv": 1,
"nombre_heures": 7.5,
"created_at": "2021-09-16T13:55:00.000000Z",
"updated_at": "2021-09-16T13:55:03.000000Z"
}
And the object to insert into the existing json object :
{
"id": 1,
"evenement_type_id": 1,
"reservation_id": 1,
"posinreserv": 1,
"campus_id": 1,
"comment": null,
"created_at": null,
"updated_at": null
}
We tried json_encode and json_decode, without success :
$reservation = json_decode($reservation, true)
All this with Laravel 7 (not is js)
Thank you.
$data1 = '{
"id": 1,
"horaire_id": 1,
"json": "{"i": "idHoraire1-NumReservation1", "x": 3, "y": 2, "w":5, "h": 3, "j": 0}",
"num_reserv": 1,
"nombre_heures": 7.5,
"created_at": "2021-09-16T13:55:00.000000Z",
"updated_at": "2021-09-16T13:55:03.000000Z"
}';
$data2 = '{
"id": 1,
"evenement_type_id": 1,
"reservation_id": 1,
"posinreserv": 1,
"campus_id": 1,
"comment": null,
"created_at": null,
"updated_at": null
}';
Laravel
$array = array_merge($data1->toArray(), $data2->toArray());
PHP
$array = array_merge(array($data1), array($data2));
You can use the spread operator: (note json objects are just arrays in php, assuming you've json_decoded it)
$result = [...$array_1, ...$array_2]
or
$result = array_merge($array_1, $array_2)
I have a nested json object:
{
"51": {
"wheels": 10,
"id": 1,
"name": "truck"
},
"55": {
"wheels": 4,
"id": 33,
"name": "Car"
},
"88": {
"wheels": 2,
"id": 90,
"name": "Bike"
}
}
I would like to filter by ID but only return the wheels so ie.
Filter ID = 33 which would return 4.
I have tried using the .filter function but I get an error: filter is not a function which I assume is because this is not an array. I have tried to replicate using answer here:
How to filter deeply nested json by multiple attributes with vue/javascript
Without success because the json has a key (51, 55, 88) so I am stumped.
Thanks for the help in advance.
You can use Object.values to convert the object into an array and then use find method on it to retrieve the specific object. Something like:
Object.values(obj).find(val => val.id === 33)?.wheels
let obj = {
"51": {
"wheels": 10,
"id": 1,
"name": "truck"
},
"55": {
"wheels": 4,
"id": 33,
"name": "Car"
},
"88": {
"wheels": 2,
"id": 90,
"name": "Bike"
}
}
console.log(Object.values(obj).find(val => val.id === 33)?.wheels)
How to GROUP BY multiple levels in Laravel. I've tried this code.
I've also used toArray() then array_values(), but same result as using values()
EDIT: Sorry, I wrote value() instead of values()
When using values(), product_name not showing.
// Controller
$products = DB::table('product_registrations')
// ->select(['product_name', 'color'])
->join('colors', 'colors.id', '=', 'product_registrations.color_id')
->join('sizes', 'sizes.id', '=', 'product_registrations.size_id')
->join('products', 'products.id', '=', 'product_registrations.product_id')
->get()
->groupBy(['product_name', 'color']);
// ->values(); // I've used values(), it worked but first level groupBy name missing
return response()->json(['products' => $products]);
---
I want something like:
products: [
product1: [
color1: {},
color2: {}
]
]
Without values()
{
"products": {
"light blue dress": {
"Ягаан": [
{
"id": 1,
"product_id": 1,
"color_id": 1,
"size_id": 6,
"color": "Ягаан",
"product_name": "light blue dress",
}
],
},
}
}
With values()
{
"products": [
{
"Ягаан": [
{
"id": 1,
"product_id": 1,
"color_id": 1,
"size_id": 6,
"color": "Ягаан",
"product_name": "light blue dress",
}
],
}
]
}
Try this one. I also have problem on this last week but I manage to get through.
$products::latest()->get();
$products = products->groupBy(function($product) {
return $product->name;
});
$products = products->map(function($product) {
return $product->groupBy(function($prod) {
return $prod->color;
});
});
return $products;
You can also optimize this method by using array_only this method is only for laravel
I am new in laravel and working on a project where I need to get the data from different tables in Laravel 5.7
Suppose I have 3 tables:
Main Table from which I need to fetch the data
Secondary Table 1
Secondary Table 2
Main Table Columns
id (auto increment primary key)
task_name (I have stored secondary table name here)
tid (task id)
assigned_to
description
Here is my code
public function viewTasks(){
$task_logs = TaskLog::orderBy('id','desc')->get();
foreach($task_logs as $task_log)
{
$table_name = $task_log['task_name'];
if(Schema::hasTable($table_name))
{
$tasks[] = DB::table($table_name)->where('id', $task_log->tid)->first();
}
}
return $tasks;
And here is the output:
[
{
"id": 220,
"uId": 324,
"document_name": "Photo Id",
"document_image": "image1.jpg",
"created_at": "2018-12-30 09:56:24",
"updated_at": "2018-12-30 09:56:24",
"status": 1,
},
{
"id": 114,
"uId": 382,
"makeModel": "Motorola 501",
"PhoneTitle": "New launched",
"price": "500",
"dealerName": "",
"created_at": "2018-12-30 09:56:24",
"updated_at": "2018-12-30 09:56:24",
"status": 1,
}
]
Output what I need:
[
{
"id": 220,
"uId": 324,
"document_name": "Photo Id",
"document_image": "image1.jpg",
"created_at": "2018-12-30 09:56:24",
"updated_at": "2018-12-30 09:56:24",
"status": 1,
"task_name": "documents",
"assigned to": 3,
"Description": "Description here",
},
{
"id": 114,
"uId": 382,
"makeModel": "Motorola 501",
"PhoneTitle": "New launched",
"price": "500",
"dealerName": "",
"created_at": "2018-12-30 09:56:24",
"updated_at": "2018-12-30 09:56:24",
"status": 1,
"task_name": "wishlists",
"assigned to": 2,
"Description": "Description here"
}
]
I have tried different ways using array_push function and array_merge etc to merge two arrays in a single array but no one worked. I don't know how can I implement this.
Please let me know if any information is missing in this question to understand and answering the question. Any help would be greatly appreciated. Thanks in advance.
you can merge different objects in PHP, In this case you have to use put the variables in the single array in foreach and you will get the required format of data.
public function viewTasks(){
$array = [];
$task_logs = TaskLog::orderBy('id','desc')->get();
foreach($task_logs as $task_log)
{
$table_name = $task_log['task_name'];
if(Schema::hasTable($table_name))
{
$tasks[] = DB::table($table_name)->where('id', $task_log->tid)->get();
$array[] = array_merge($tasks,$task_log);
}
}
return $array;
Can you try this... hope it work
public function viewTasks(){
$i = 0;
$task_logs = TaskLog::orderBy('id','desc')->get();
foreach($task_logs as $task_log)
{
$table_name = $task_log['task_name'];
if(Schema::hasTable($table_name)){
$tasks[$i] = DB::table($table_name)->where('id', $task_log->tid)->first();
$tasks[$i]['task_name'] = $task_log['task_name'];
$tasks[$i]['assigned_to'] = $task_log['assigned_to'];
$tasks[$i]['description'] = $task_log['description'];
$i++;
}
}
return $tasks;