How can I put counter in laravel? - php

In my leave management module I have a field , which displays count of employee took total leave and which are approved,
But unfortunately I can't get the count.
will anyone help me please???
Here is code of my view file
<div class="row">
<label class="col-md-6"><strong> Total Leave in this month </strong>/label>
<div class="col-md-6">
{{$count}}
</div>
</div>
Here is my code of controller file
public function handleLeave($id)
{
$employeeName = User::all();
$leaves = LeaveManagement::find($id);
$count = LeaveManagement::where('status', '=', 'Approved')->count();
return view('pages.leavelist', compact('leaves', 'id', 'count', 'employeeName'));
}

Related

How to display multiple datasets by month in highchart?

I have a database called sales which I'm trying to display in my chart like this but can't.
id
products
earnings
created_at
1
Jasmine
50
2023-01-14 18:55:34
2
How to cook
150
2023-01-14 18:55:34
3
Jasmine
100
2023-01-14 18:55:34
4
Dictionary
200
2023-01-14 18:55:34
5
How to cook
70
2023-02-20 17:23:54
It is my first time trying to do it in chart and tried other codes from tutorials
and ended up with this result
I'm trying to display it like the first chart, but instead by month with multiple datasets where the month will contain the name of the products and its earning on that month. like this
Pardon my unsightly editing
This is the working code that I managed to follow and do, but don't know how to modify it to obtain the desired output. I tried but gets an error, so I put it back.
$now = Carbon::now();
$yr = $now->format('Y/m/d');
//monthly
{
$m= $now->format('m');
$date_start = Carbon::create(date('Y'), "1");//january start
$data=[];
$monthdata=[];
$x=0;
for ($month = $m; $x <= 7; $month++)
{
$x=$x+1;
$date = Carbon::create(date('Y'), $month);
$date_end = $date->copy()->endOfMonth();
$saledate = DB::table('sales')
->select(DB::raw('sum(earnings) as sale'))
->where('created_at', '>=', $date)
->where('created_at', '<=', $date_end)
->get();
$sum=0;
foreach ($saledate as $row)
{
$sum=$row->sale;
}
array_push($data,$sum);
array_push($monthdata,$date->format('M'));
}
$saleChart1= new UserChart;
$saleChart1->labels($monthdata);
$saleChart1->dataset('Sales', 'bar',$data )->options([
'color' => '#2596be',
]);
}
Inside my blade file,
<div class="col-lg-6 mb-5">
<div class="card card card-raised h-100 ">
<div class="card-header text-dark bg-success px-4" style="background-color:#198754 !important">
<i class="fas fa-chart-area me-1 text-white"></i>
Monthly Sales
</div>
<div class="card-body bg-white">
<div class="col-lg-12 " >
<div id="myAreaChart1" class="mt-4" style="height: 300px;">
{!! $saleChart1->container() !!}
<script src=https://cdnjs.cloudflare.com/ajax/libs/echarts/4.0.2/echarts-en.min.js charset=utf-8></script>
{!! $saleChart1->script() !!}
</div>
</div>
</div>
</div>
</div>
My UserChart class,
<?php
namespace App\Charts;
use ConsoleTVs\Charts\Classes\Chartjs\Chart;
class UserChart extends Chart
{
/**
* Initializes the chart.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
}
Please help, can't find other tutorials, all I found now are pie charts and line graphs and doesn't display similar to what I'm looking for. What should I do to achieve the desired output?
It doesn't seem like ConsoleTVs\Charts\Classes\Chartjs\Chart has that capability. However, you might be able to get ConsoleTVs\Charts\Classes\Echarts\Chart to work closer to what you'd need.
If I were you I'd change your UserChart class to
<?php
namespace App\Charts;
use ConsoleTVs\Charts\Classes\Echart\Chart;
class UserChart extends Chart
{
/**
* Initializes the chart.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
}
Then using example from https://echarts.apache.org/examples/en/editor.html?c=bar-label-rotation
you should be able to mold your data into the correct format.
It seems as though most of the setup is pushed into an option array. Some of which you can see on the class itself https://github.com/ConsoleTVs/Charts/blob/main/src/Classes/Echarts/Chart.php
You should be able to set the options with $saleChart1->options([//...]);
Happy coding :-)

How to display multiple data from a checkbox when checked?

I have multiple checkboxes, I want to display an array of data when multiple checkboxes are clicked, but only one value is displayed, how to display an array ?What is the problem?
<div class="form-group" >
<h5>Your languages</h5>
<div class="col-md-12">
#foreach($langs as $key => $lang)
<input type="checkbox" name="foo[]" value="{{$key}}">
<label>{{ $lang }}</label>,
#endforeach
</div>
</div>
To controller
public function Method(Request $request)
{
foreach((array)$request->input('foo') as $value){
$file = 'la.txt';
file_put_contents($file,$value );
}
return redirect()->route('profile');
}
I want to display the value of all these three checkboxes, but only the data of one of them is displayed
enter image description here
Hmm - let me guess the issue, I think that you should return the values while you return back to the profile view. I think also the problem is not in the first load of the profile view, because you have to pass the langs array, but the issue happens when you click the checkboxes to store the data in the controller's method, so your code must be like so
public function storeData(Request $request)
{
foreach($request->input('foo') as $value){
$file = 'la.txt';
file_put_contents($file, $value);
}
$yourLangsArray = ["English", "Arabic"];
return redirect()->route('profile')->with('langs', $yourLangsArray);
}

laravel pagination returns different page

I am working on a laravel project, where I get data from an API then I want to display it on pages. I want the return to be spread out across 4 pages, each page with 10 results each. What I have so far, seems like it should work, but I am missing one piece, so any advice and help would be appreciated. So this is how it is suppose to work with code:
1) The users types in a book title in a search box.
<form method=POST action='/search'>
#csrf
<input type="text" name="search_term"/>
<input type="submit" value="Search"/>
</form>
2) there input is then sent to my controller, which queries the google books api.
class search extends Controller {
public function search(){
$current_page = LengthAwarePaginator::resolveCurrentPage();
echo $current_page;
$term = request('search_term');
$term = str_replace(' ', '_', $term);
$client = new \Google_Client();
$service = new \Google_Service_Books($client);
$params = array('maxResults'=>40);
$results = $service->volumes->listVolumes($term,$params);
$book_collection = collect($results);
$current_book_page = $book_collection->slice(($current_page-1)*10,10)->all();
$books_to_show = new LengthAwarePaginator($current_book_page,count($book_collection),10,$current_page);
return view('library.search')->with(compact('books_to_show'));
}
}
3) the results are then displayed on my blade
#extends('home')
#section('content')
#foreach($books_to_show as $entries)
<div class="row">
<div class="col-sm-auto">
<img class="w-50 img-thumbnail" src={{$entries['volumeInfo']['imageLinks']['smallThumbnail']}}/>
</div>
<div class="col-sm">
{{$entries['volumeInfo']['title']}}<br/>
#if($entries['volumeInfo']['authors']!=null)
by:
#foreach($entries['volumeInfo']['authors'] as $authors)
{{$authors}}
#endforeach
#endif
</div>
</div>
#endforeach
{{$books_to_show->links()}}
#endsection
This all works fine and as expected. I get 10 results on the view, and then I have a bar at the bottom which give shows me 4 different pages to choose from.
When I first type in a search term such as "William Shakespeare" My page url is:
localhost:8000/search
But, when I click on any of the pages my url becomes:
http://localhost:8000/?page=2
I understand that the ?page=* is how the pagination determines which page you are viewing, and that should be sent back to the controller. But, I am missing something on sending it back to the controller I think.
Still kind of fresh to this, so any advice is more then greatly appreciated.
LengthAwarePaginator accepts a 5th parameter in its constructor: an array of options.
the path option
$books_to_show = new LengthAwarePaginator($current_book_page, count($book_collection), 10, $current_page, [
// This will fix the path of the pagination links
'path' => LengthAwarePaginator::resolveCurrentPath()
]);
By the way, on a totally different matter, Laravel makes your life easier by slicing the collection for you, check it out:
$current_book_page = $book_collection->forPage($current_page, 10);
Hope it helps :)

Laravel - How to dynamically load content in same view after submit in drop down list

After selecting an option from drop down list, I am submitting it to a controller function which is returning required data in a different view. I want it to load the view in the same page (possibly inside a div) as the drop down list where I am submitting it. (I am new to Laravel and PHP)
The following is my clinic.blade.php file which lists clinics in drop down.
{!! Form::open(['route' => 'clinicIndex', 'method' =>
'POST'])!!}
<label> Select Clinics </label>
<select name = "clinic">
#foreach($clinics as $clinic)
<option value="{{$clinic->clinicID}}"> {{$clinic->clinicName}}</option>
#endforeach
</select>
{{Form::submit('DisplayDoctors', ['class' => 'btn btn-outline-
primary'])}}
{{Form::close()}}
The Submit is accessing my controller method via clinicIndex Route defined as below in web.php
Route::post('/clinicTest', 'ClinicController#clinicIndex')-
>name('clinicIndex');
This is the function in controller
public function clinicIndex(Request $request)
{
$selectedClinic = $request->clinic;
$clinicInfo = Clinic::where('id', '=', $selectedClinic)->get();
$dbArray = DB::connection('mysql2')->select("SELECT * FROM bp_admin.tdbsrv WHERE iClinicId = $selectedClinic");
$dbInfo = $dbArray[0];
$remoteConnection = DatabaseConnection::setConnection($dbInfo);
$doctors = $remoteConnection->select("SELECT tUsers.sSalutation, tLocationPhysician.iPhysicianId, tUsers.sFirstName,
tUsers.sLastName,tUsers.iPhysNum,tUsers.sDateHired,
tPhysician.bLocum,tPhysician.bResident,
tPhysician.dStartDay,tPhysician.dEndDay
from tUsers
inner join tLocationPhysician
inner join tPhysician
where
tLocationPhysician.iLocationId = $selectedClinic
and tPhysician.iId = tLocationPhysician.iPhysicianId
and tPhysician.iPhysNum = tUsers.iPhysNum
and tUsers.bArchived =0
and tLocationPhysician.bArchived =0
and tPhysician.bArchived =0
order by tUsers.sFirstName asc");
return view('pages.show')->with('doctors', $doctors);
}
You can see that it is returning the table in a different view (opens a new page). Instead I want it to load the table in same view after submitting my selection from drop down.
I tried doing this in my clinic.blade.php
<div class="container" id="dispDoctors"> </div>
And added an ajax script in the same view
<script>
function loadDocContent(){
$('#dispDoctors').load('/loadDocs');
}
</script>
For testing dynamic load, I defined the function for "/loadDocs" same as my controller function clinicIndex() in web.php. I am stuck how to proceed from here. As I am not sure how to pass my drop down selection to the jquery function.
I finally figured out that it can be done using ajax. I am returning the view as a html and loading it in my original view.
This is my blade file
#extends('layouts.apptest')
#section('content')
#include('inc.messages')
<br>
<div class="container">
<div class="col-lg-4">
{{Form::open(array('url'=>'', 'files'=>true))}}
<div class="form-group">
<label for="">Select clinics</label>
<select class="form-control input-sm" name="clinic" id="clinic">
#foreach($clinics as $clinic)
<option value="{{$clinic->clinicID}}"> {{$clinic->clinicName}}</option>
#endforeach
</select>
</div>
{{Form::close()}}
</div>
</div>
<div class="container" id="dispDoctors">
</div>
#endsection
#section('script')
<script>
$('#clinic').on('change', function(e){
console.log(e);
var clinic_sel = e.target.value;
//ajax
$.get('/ajax-clinic?clinic_sel=' +clinic_sel, function(data){
//success data
$('#dispDoctors').html(data.html);
});
});
</script>
#endsection
and this is the route I am setting up in web.php
Route::get('/ajax-clinic', function(){
$clinic_sel = Input::get('clinic_sel');
$clinicInfo = Clinic::where('id', '=', $clinic_sel)->get();
$dbArray = DB::connection('mysql2')->select("SELECT * FROM bp_admin.tdbsrv WHERE iClinicId = $clinic_sel");
$dbInfo = $dbArray[0];
$remoteConnection = DatabaseConnection::setConnection($dbInfo);
$doctors = $remoteConnection->select("SELECT tUsers.sSalutation, tLocationPhysician.iPhysicianId, tUsers.sFirstName,
tUsers.sLastName,tUsers.iPhysNum,tUsers.sDateHired,
tPhysician.bLocum,tPhysician.bResident,
tPhysician.dStartDay,tPhysician.dEndDay
from tUsers
inner join tLocationPhysician
inner join tPhysician
where
tLocationPhysician.iLocationId = $clinic_sel
and tPhysician.iId = tLocationPhysician.iPhysicianId
and tPhysician.iPhysNum = tUsers.iPhysNum
and tUsers.bArchived =0
and tLocationPhysician.bArchived =0
and tPhysician.bArchived =0
order by tUsers.sFirstName asc");
$returnView = view('pages.test')->with('doctors', $doctors)->render();
return response()->json(array('success' =>true, 'html' =>$returnView));
});
You can see in my blade file that I am loading the html returned by the ajax call.
Thanks to other answers as well!
Use axios call to submit form and receive response from controller.
Example code here https://stackoverflow.com/a/57523553/5728565
You should use ajax or Pjax to load the dynamically content in the web page,
When using Ajax or Pjax you must return response in json format from controller. follow this link

I could not retrive values sent by controller in view file

I am using codeigniter.When I perform add function I need to calculate tax. I have tax value in a table I need to fetch the value from the table and use it in my view page.
public function view()
{
$this->load->library('session');
$data['service_detail']=$this->session->userdata('service_detail');
$data['tax'] = $this->settings_model->get_tax();
$data['main_content'] = 'admin/service/view';
$this->load->view('includes/template', $data);
}
In model file I have this function by which I get the tax value from the table
public function get_tax()
{
$query = $this->db->query("SELECT company_tax13 FROM service_settings ");
$result = $query->result_array();
return $result;
}
Here is my view file where i get the tax value.
<div class="form-group">
<label for="email">Service price: <?=$service_detail['service_price']?> Rs</label>
</div>
<div class="form-group">
<label for="email">Tax Percentage : <?=$tax['company_tax13']?>%
<div class="form-group">
<?php
$tax_percentage=$tax['company_tax13'];
if(strstr($service_detail['service_tax'],"inclusive")==true) {
$taxamount=$service_detail['service_price']-($service_detail['service_price']/(1+($tax_percentage/100)));
$grand=$service_detail['service_price'];
}
else {
$taxamount=($service_detail['service_price']*(1+($tax_percentage/100)))-$service_detail['service_price'];
$grand=$taxamount+$service_detail['service_price'];
}
?>
<label for="email">Tax Amount : <?php echo $taxamount; ?> Rs</label>
<div class="form-group">
<label for="email">Grand Amount : <?php echo $grand; ?> Rs</label>
</div>
I could not get the tax value in my page.
Can someone help me. I do not know the reason why i get no value in my output.
Edit 01
In service_detail['service_price'] contains either inclusive or exclusive. with that value I use strstr() to compare that string.
use row_array() instead of result_array() because result_array() returns the first value in index 0 and you should call:
$tax[0]['company_tax13'];

Categories