How to get leave between two days in Laravel - mysql

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.

Related

Laravel whereJsonContains query

I have following JSON code in my database table
[
{
"indentifier": "category",
"name": "XXXXXXX",
"products": [
{
"indentifier": "childproduct",
"name": "XXXX",
"price": 15,
"sku": "+0094",
"factorynumber": "156670",
"unit": "50 Stk/Pck",
"kp": "50",
"discountCode": "V",
"from": "2020-01-01",
"to": "2099-01-01"
},
...
]
},
{
"indentifier": "category",
"name": "XXXXXXX",
"products": [
{
"indentifier": "childproduct",
"name": "XXXX",
"price": 29,
"sku": "+0104",
"factorynumber": "156680",
"unit": "50 Stk/Pck",
"kp": "50",
"discountCode": "V",
"from": "2020-01-01",
"to": "2099-01-01"
},
....
]
}
]
Now how I can implement for searching the sku in this JSON in "when" keyword? My following code is here:
$date = now()->toDateString();
if ($request->keyword != "") {
$keyword = $request->keyword;
} else {
$keyword = false;
}
$products = Product::whereJsonContains('catalogs', intval($request->catalog))
->whereDate('from', '<=', $date)
->whereDate('to', '>', $date)
->orderBy('category', 'ASC')
->orderBy('sort', 'ASC')
->where('active', 1)
})
->when(
$keyword,
function ($query, $keyword) use ($category) {
$query->where('sku', 'like', '%' . $keyword)
->orWhere('factorynumber', 'like', $keyword)
->orWhere('name', 'like', '%' . $keyword . '%')
->orWhereJsonContains('childs', ['products->sku' => $keyword])
->where('active', 1)
});
}
)->get();
The line with
->orWhereJsonContains('childs', ['products->sku' => $keyword])
will not work... what is the right syntax for the query? At moment there are 0 results if search for child sku field.
Thanks for helping
orWhereJsonContains() doesn't exist in Laravel, but whereJsonContains(), and it works with arrays and not the associative arrays. Also you have to make sure the data from json goes as the first argument, not the second like this:
whereJsonContains('table_column_name_with_json_in_it->json_value_key',$requiredValue)
In that case this query of yours:
->orWhereJsonContains('childs', ['products->sku' => $keyword])
Should be something like this:
->WhereJsonContains('product->sku', $sku)

how to change laravel db query builder bracket

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);

JSON data from GET method

How can I retrieve json data in .json file from API get query of product?
Example: https://api.abcd.com/v1/products/search.json?q=ball
header[key=abc, value=xyz]
From get query fetch json data from postman like
{
"Results": [
{
"Id": 5481192,
"Name": " Shirt",
"Description": " tweens. 100% Cotton.",
"ShortDescription": " Raglan Shirt",
"Number": "4253121",
"ImageUrl": "media/295428",
"VirtualSampleImages": [
{
"Id": 2245428,
"ImageUrl": "virtualsample/2529548"
}
],
"ConfigId": "23",
"Supplier": {
"Id": 613,
"Name": "a",
"AsiNumber": "3529721",
"Phone": {
"Work": "(451) 488-0417",
"$index": 1
}
},
"Price": {
"Quantity": 11,
"Price": 133.7,
"Cost": 61.85,
"DiscountCode": "P",
"CurrencyCode": "USD"
},
"IsNew": false,
"IsConfirmed": false,
"HasVirtualSample": true
}
],
"Selections": {},
"Dimensions": {},
"Links": {
"Self": "?q=shirts&page=1&rpp=1",
"Next": "?q=shirts&page=2&rpp=1"
},
"Query": "shirts",
"Breadcrumb": "\"shirts\"",
"Page": 1,
"ResultsPerPage": 21,
"ResultsTotal": 78,
"SuppliersTotal": 6677,
"CompletedIn": 7
}
I want to save the json data to .json file (automatically) after that to MySQL database with individual columns.
You can simply use curl for the save-to-file process.
curl 'https://api.abcd.com/v1/products/search.json?q=ball' -H 'Accept: application/json, text/plain, */*' -H 'key: abc' -H 'value: xyz' -o dump.json
Then, you can load this file into table with LOAD_FILE :
INSERT INTO table_name (STAMP,file_content) VALUES(NOW(),LOAD_FILE("dump.json"));
The whole process depends on you scripting/programming language. Can you tell us more about your technical context ?
$curl = curl_init();
$options=array(CURLOPT_URL=>"http://api.abc.com/v1/products/search.json?q=ball",CURLOPT_RETURNTRANSFER =>true,
CURLOPT_ENCODING =>"",CURLOPT_FOLLOWLOCATION =>true,CURLOPT_MAXREDIRS => 10,CURLOPT_TIMEOUT=>30,CURLOPT_HTTP_VERSION=>CURL_HTTP_VERSION_1_0,
CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_POSTFIELDS=>"",
CURLOPT_HTTPHEADER=> array("authorization: AsiMemberAuth client_id=50041351&client_secret=55700485cc39f1",
"cache-control: no-cache"), CURLOPT_HEADER=> true);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
}
else
{
echo $response;
}

I want to get data in single array from different tables in Laravel 5.7

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;

Ruby API call to get data from complex json

I'm making an API GET call using Ruby - the call is made to a Learning Management System and returns the following JSON:
{
"id": 12345,
"body": null,
"url": null,
"grade": "75",
"score": 75,
"submitted_at": "2020-05-02T11:30:53Z",
"assignment_id": 9876,
"user_id": 1111,
"submission_type": "online_upload",
"workflow_state": "graded",
"grade_matches_current_submission": true,
"graded_at": "2017-06-05T08:47:49Z",
"grader_id": 2222,
"attempt": 1,
"cached_due_date": "2020-05-03T15:00:00Z",
"excused": false,
"late_policy_status": null,
"points_deducted": null,
"grading_period_id": null,
"late": false,
"missing": false,
"seconds_late": 0,
"entered_grade": "75",
"entered_score": 75,
"preview_url": "https://etcetc",
"turnitin_data": {
"attachment_33333": {
"status": "scored",
"object_id": "44444444",
"similarity_score": 0,
"web_overlap": 0,
"publication_overlap": 0,
"student_overlap": 0,
"state": "none"
}
},
"attachments": [
{
"id": 33333,
"uuid": "kjsdkjhsdfkhsfd",
"folder_id": 55555,
"display_name": "Submission.pdf",
"filename": "Submission.pdf",
"content-type": "application/pdf",
"url": "https://etcetc",
"size": 2668226,
"created_at": "2020-05-02T11:30:51Z",
"updated_at": "2020-06-06T15:01:46Z",
"unlock_at": null,
"locked": false,
"hidden": false,
"lock_at": null,
"hidden_for_user": false,
"thumbnail_url": null,
"modified_at": "2020-05-02T11:30:51Z",
"mime_class": "pdf",
"media_entry_id": null,
"locked_for_user": false,
"preview_url": "api/etcetc"
}
],
"submission_comments": [
{
"id": 99999,
"comment": "here’s a comment",
"author_id": 1,
"author_name": "Mickey Mouse",
"created_at": "2020-05-15T12:54:08Z",
"edited_at": null,
"avatar_path": "/images/users/1",
"author": {
"id": 1,
"display_name": " Mickey Mouse ",
"avatar_image_url": "https://etcetc",
"html_url": "https://etcetc"
}
},
{
"id": 223344,
"comment": "another comment",
"author_id": 2,
"author_name": "Donald Duck",
"created_at": "2020-06-05T10:48:51Z",
"edited_at": null,
"avatar_path": "/images/users/2",
"author": {
"id": 2,
"display_name": "Donald Duck",
"avatar_image_url": "https://etcetc",
"html_url": "https://etcetc"
}
}
]
}
I need to be able to retrieve specific values from "submission_comments", namely the values for "comment", "author_id" and "author_name". At the moment the best I can do is retrieve "submission_comments" as one big entity. Here's how I'm getting that far:
require 'typhoeus'
require 'link_header'
require 'json'
require 'csv'
the_url = 'https://etctetc'
token = 'mytoken'
api_endpoint = '/api/etc'
output_csv = 'C:\Users\me\Desktop\Ruby Canvas course\assignment_comments.csv'
CSV.open(output_csv, 'wb') do |csv|
csv << ["user_id", "TII", "marker"]
end
request_url = "#{the_url}#{api_endpoint}"
count = 0
more_data = true
while more_data
get_comments = Typhoeus::Request.new(
request_url,
method: :get,
headers: { authorization: "Bearer #{token}" }
)
get_comments.on_complete do |response|
#get next link
links = LinkHeader.parse(response.headers['link']).links
next_link = links.find { |link| link['rel'] == 'next' }
request_url = next_link.href if next_link
if next_link && "#{response.body}" != "[]"
more_data = true
else
more_data = false
end
if response.code == 200
data = JSON.parse(response.body)
data.each do |comments|
CSV.open(output_csv, 'a') do |csv|
csv << [comments['id'], comments['turnitin_data'], comments['submission_comments']]
end
end
else
puts "Something went wrong! Response code was #{response.code}"
end
end
get_comments.run
end
puts "Script done running"
I'm new to this (the ruby code is based on an exercise so I may not fully understand it)- any help/advice would be really appreciated!
EDIT: I should also note that this isn't the total JSON response I'm dealing with - this is just one of ten items that are returned
"submission_comments": [
{
"id": 99999,
}
]
the [] means it is array. {} means it is an object.
So you probably need to do something like this:
json["submission_comments"].first["id"]
or better iterate through it:
ids = json["submission_comments"].map{|comment| comment["id"]}
I'm able to get the variables you need if you can read the JSON file in as text, then use Ruby's JSON.parse(...) method on it. I think the main problem is that JSON uses null but Ruby hashes use nil. You could do a string replace or try something like this (I did not modify your JSON, only put it into a single quoted string):
json_text = '{
"id": 12345,
"body": null,
"url": null,
"grade": "75",
"score": 75,
"submitted_at": "2020-05-02T11:30:53Z",
"assignment_id": 9876,
"user_id": 1111,
"submission_type": "online_upload",
"workflow_state": "graded",
"grade_matches_current_submission": true,
"graded_at": "2017-06-05T08:47:49Z",
"grader_id": 2222,
"attempt": 1,
"cached_due_date": "2020-05-03T15:00:00Z",
"excused": false,
"late_policy_status": null,
"points_deducted": null,
"grading_period_id": null,
"late": false,
"missing": false,
"seconds_late": 0,
"entered_grade": "75",
"entered_score": 75,
"preview_url": "https://etcetc",
"turnitin_data": {
"attachment_33333": {
"status": "scored",
"object_id": "44444444",
"similarity_score": 0,
"web_overlap": 0,
"publication_overlap": 0,
"student_overlap": 0,
"state": "none"
}
},
"attachments": [
{
"id": 33333,
"uuid": "kjsdkjhsdfkhsfd",
"folder_id": 55555,
"display_name": "Submission.pdf",
"filename": "Submission.pdf",
"content-type": "application/pdf",
"url": "https://etcetc",
"size": 2668226,
"created_at": "2020-05-02T11:30:51Z",
"updated_at": "2020-06-06T15:01:46Z",
"unlock_at": null,
"locked": false,
"hidden": false,
"lock_at": null,
"hidden_for_user": false,
"thumbnail_url": null,
"modified_at": "2020-05-02T11:30:51Z",
"mime_class": "pdf",
"media_entry_id": null,
"locked_for_user": false,
"preview_url": "api/etcetc"
}
],
"submission_comments": [
{
"id": 99999,
"comment": "here’s a comment",
"author_id": 1,
"author_name": "Mickey Mouse",
"created_at": "2020-05-15T12:54:08Z",
"edited_at": null,
"avatar_path": "/images/users/1",
"author": {
"id": 1,
"display_name": " Mickey Mouse ",
"avatar_image_url": "https://etcetc",
"html_url": "https://etcetc"
}
},
{
"id": 223344,
"comment": "another comment",
"author_id": 2,
"author_name": "Donald Duck",
"created_at": "2020-06-05T10:48:51Z",
"edited_at": null,
"avatar_path": "/images/users/2",
"author": {
"id": 2,
"display_name": "Donald Duck",
"avatar_image_url": "https://etcetc",
"html_url": "https://etcetc"
}
}
]
}'
Part I added:
ruby_hash = JSON.parse(json_text)
submission_comments = ruby_hash["submission_comments"]
submission_comments.each do |submission_comment|
comment = submission_comment["comment"]
author_id = submission_comment["author_id"]
author_name = submission_comment["author_name"]
puts "Comment: #{comment}, Author ID: #{author_id}, Author Name: #{author_name}\n\n"
end
Terminal Result:
=> Comment: here’s a comment, Author ID: 1, Author Name: Mickey Mouse
=> Comment: another comment, Author ID: 2, Author Name: Donald Duck
Edit: I added a jenky af one-liner version just for fun (presuming the json_text variable above is already initialized)
JSON.parse(json_text)["submission_comments"]
.map{|txt| puts(["comment","author_id","author_name"]
.map{|k| k.instance_eval{"#{upcase}: #{txt[to_s]}"}}.join(', '))}
COMMENT: here’s a comment, AUTHOR_ID: 1, AUTHOR_NAME: Mickey Mouse
COMMENT: another comment, AUTHOR_ID: 2, AUTHOR_NAME: Donald Duck