making report in laravel By Day Month Year - php

My Code Sum Products and quantity and price but i need 3 functions for day year month in first i will get total of products in every day next in every month and last in every year
the Code
$product_orders = \App\OrderProduct::select(DB::raw('sum(line_total) as total_line'),
DB::raw('sum(qty) as qty') , 'product_id','line_total','created_at')->
orderBy('created_at')->groupBy('product_id')->get();
DB
id , prdouct_id ,order_id, qty ,unit_total , line_total , created_at , updated_at

##for grouping you can use it like these
public function day(){
$products= OrderProduct::select(
DB::raw('DAY(created_at) as day'),DB::raw('sum(line_total) as total_line') , 'product_id','qty','line_total','created_at')->groupBy('day','product_id')->get();
}
public function month(){
$products= OrderProduct::select(
DB::raw('MONTHNAME(created_at) as month'),
DB::raw('sum(line_total) as total_line') , 'product_id','qty','line_total','created_at')->groupBy('month','product_id')->get();
}
public function year(){
$products= OrderProduct::select(
DB::raw('YEAR(created_at) as year'),
DB::raw('sum(line_total) as total_line') , 'product_id','qty','line_total','created_at')->groupBy('year','product_id')->get();
}
try this and let me know what happened

try this:
$Rspatients = DB::table('reports')
->select(
DB::raw("day(created_at) as day"),
DB::raw("Count(*) as total_patients"))
->orderBy("created_at")
->groupBy(DB::raw("day(created_at)"))
->get();
$result_patients[] = ['day','Patients'];
foreach ($Rspatients as $key => $value) {
$result_patients[++$key] = [$value->day,$value->total_patients];
}
then you can pass it to your view like this:
return
view('Dashboard.index')
->with('result_patients',json_encode($result_patients));
I used google charts that is why I sent my data as a json to the view, the data is then feed to the line chart of google chart.

Related

Get latest value in the group of records

I have this records table which I save weight, age and other biometrics in it.
Now I want to fetch the latest value of every biometric for every day so I can draw a chart.
The piece of code I'm using to fetch data from db before processing it is like the following:
Records::where("user",$uid)->
where("type", "biometric" )-> // record type
where("fk", $bid )-> //biometric type
where("datetime","<" ,$range->max)->
where("datetime",">" ,$range->min)->
groupBy( "datee" )->
selectRaw(" max(amount) as 'damount' , max(unit) as 'unit' , date(datetime) as 'datee' ")->
orderBy("datee","desc")->
get();
// !! Should change max values with the latest record in the group !!
Which datee is date of the day.
Say some users add more than one weight biometrics in a day so unit and damount should be the unit and value of lastest record of that day.
What can I use instead of max() to achieve this?
Thanks in advance,
Hope this helps:
Records::where("user",$uid)
->where(["type" => "biometric", "fk" => $bid])
->whereBetween(DB::raw("DATE('datetime')"), array($range->max, $range->min))
->groupBy("datetime")->latest()->get();
Can you try this
Records::where("user",$uid)
->where("type", "biometric")
->where("fk", $bid)
->where("datetime","<" ,$range->max)
->where("datetime",">" ,$range->min)
->latest()
->groupBy('datetime')
->get();

Carbon divide records into weeks and months

I have a record where I am getting data with timestamps (created_at, updated_at) for last 4 months. Next, I want to divide this data into week wise and month wise (last 4 weeks and last 4 months.)
What I am trying is to manually create variables for each months and then write if logic to enter data into each month. Is there any function that already does it?
// for student population - Last 4 months data
$from = Carbon::now()->subMonth(4);
$to = Carbon::now();
$invoice =invoice::where('instructor_id', '=', $id)
->whereBetween('created_at',[$from,$to])->get();
$week_1=$week_2=$week_3=$week_4=$month_1=$month_2=$month_3=$month_4=[];
// write if logic and enter data for each week separately
No, there is no function that already does it, afaik, in Eloquent or Carbon.
I would suggest looping through the Eloquent Collection.
Here is a hint for you :
$from = Carbon::now()->subMonth(4);
$to = Carbon::now();
$invoices = invoice::where('instructor_id', '=', $id)->whereBetween('created_at', [$from, $to])->get();
// ...
$invoicesLastWeek = $invoices->whereBetween('created_at', [
Carbon::now()->subWeeks(1)->startOfWeek(),
Carbon::now()->subWeeks(1)->endOfWeek()
]);
// ...
$invoicesTwoMonthsAgo = $invoices->whereBetween('created_at', [
Carbon::now()->subMonths(2)->startOfMonth()),
Carbon::now()->subMonths(2)->endOfMonth()
]);
// ...
I would loop and increment parameters for ->subWeeks($i)-> and ->subMonths($i)->, and populate the needed variables.
I would start setting each week vars first, so that I can pop out of the Collection all invoices in that range (for performance). Then for each month vars, I would add weekN + weekN+1 + weekN+2 + weekN+3 vars (and pop them out of the Collection as well, so that I loop faster on a Collection that is getting smaller everytime).

PHP Laravel Multiple returns

hello i have this function
//Get Total Number of Personal Leads By User ID & Requested week Through Each Day
//Get Total Number of Personal Leads By User ID & Requested week Through Each Day
$personalleads = \DB::table('leads')
->where('owned_by_id', $id) // User ID
->where('lead_source_id', 7) // 7 = Personal Lead
->whereBetween('created_at', [$weeks[$week]]) // get week through GET request & Query the data
->select(\DB::raw('DATE(created_at) as date'), \DB::raw('count(*) as pleads'))
->groupBy('date')
->get(); // Get All Data
//Get Total Number of leads Created by Managers By User ID & Requested week Through Each Day
$managerleads = \DB::table('leads')
->where('owned_by_id', $id) // User ID
->where('lead_source_id', 3) // 3 = Manager Lead
->whereBetween('created_at', [$weeks[$week]]) // get week through GET request & Query the data
->select(\DB::raw('DATE(created_at) as date'), \DB::raw('count(*) as mleads'))
->groupBy('date')
->get(); // Get All Data
//Get Total Number of leads Created by Admins By User ID & Requested week Through Each Day
$adminleads = \DB::table('leads')
->where('owned_by_id', $id) // User ID
->where('lead_source_id', 4) // 4 = Admin Lead
->whereBetween('created_at', [$weeks[$week]]) // get week through GET request & Query the data
->select(\DB::raw('DATE(created_at) as date'), \DB::raw('count(*) as aleads'))
->groupBy('date')
->get(); // Get All Data
i want to return the data of all of them
like
return $adminleads+personalleads+managerleads;
i know this is invalid but i want to display all data at once
this is the output i get when i return $personalleads only
[{"date":"2019-02-10","pleads":1},{"date":"2019-02-12","pleads":1},{"date":"2019-02-14","pleads":1}]
how can i make it something like
[{"date":"2019-02-10","pleads":1,"aleads":1,"mleads":1},{"date":"2019-02-12","pleads":1,"aleads":1,"mleads":1},{"date":"2019-02-14","pleads":1,"aleads":1,"mleads":1}]
Thank you very much
Two options you can try to join these values:
PHP will loop the results and join the data.
The queries handle the joining of data (which I cannot wrap my head around at this moment).
Not sure which one would be better. PHP looks much easier however, depenending on the system and size, my guess is that mysql can handle this much more efficient.
PHP
$pLeads = ...
$mLeads = ...
$aLeads = ...
$allLeads = $pLeads->merge($mLeads)->merge($aLeads); // Maybe there is a shorter variant.
$leads = [];
$types = ['pleads', 'mleads', 'aleads'];
$allLeads->each(function ($lead) {
// Make sure there is an array present with the date property.
data_fill($leads, $lead->date, [
'date' => $lead->date,
]);
// At this point our array looks like:
// ['2019-11-06' => ['date' => '2019-11-06']]
// Get the the type of lead.
$type = $types[array_search(array_keys($lead))];
// Set the lead amount for the type.
// Not sure if "$lead->date.$type" works. Make sure you end up with a key like 2019-11-06.pleads
data_set($leads, "$lead->date.$type", $lead->$type);
// At this point our array looks like:
// ['2019-11-06' => ['date' => '2019-11-06', 'pleads' => 1]]
});
// Remove the keys from the array.
$leads = array_flatten($leads);
// At this point our array looks like:
// [['date' => '2019-11-06', 'pleads' => 1, 'mleads' => 2, 'aleads' => 3]]
Query
SELECT
IFNULL(p.date, m.date)
pleads,
mleads
FROM (
(
SELECT
DATE(created_at) as date,
COUNT(*) pleads
FROM
leads
WHERE
...
GROUP BY
date
) p
RIGHT JOIN
(
SELECT
DATE(created_at) as date,
COUNT(*) mleads
FROM
leads
WHERE
...
GROUP BY
date
) m ON p.date = m.date
);
Both solutions have not been tested fully.

Graphic count based on the Month using Lavachart on laravel 5.2

Hello i get stuck on this proble, hope you guys can give me some advice to solve this matter. So, i want to show graph that count basen on month, how many keluhan (complain) on that month. so the table will be like january has 3 complain, febuary has 5 complain, etc (example)
public function lihatkeluhan(){
$halaman="tindaklayanan";
$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,tanggal,produk,username,area,masalah,status'))->get();
$count = count($keluhan_list); //this still not count based on month
$population = Lava::DataTable();
$population->addDateColumn('Year')
->addNumberColumn('Keluhan')
->addRow(['?',$count]);
Lava::LineChart('Population', $population, [
'title' => 'Tahun : 2017',
]);
return view('layanankonsumen.daftarkeluhan',compact('halaman','keluhan_list','lava'));
}
try query like this.
it will gives you groupby result with count of that particular month,
no need for $count = count($keluhan_list); because you will get count in result.
$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,tanggal,produk,username,area,masalah,status,count(*) as count'))
->get()
->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('m'); // grouping by months
});

laravel show "stats" ordered by date and counts

I want to show the stats of visitors on my website,
What I have:
AdminClontroller
public function index()
{
$select_stats = DB::table('visitor')->whereBetween('visit_date', array(date('Y-m-01'), date('Y-m-t')))->get();
$month = date('m');
$get_count = DB::select(DB::raw("SELECT count(*) FROM visitor WHERE MONTH(date) = $month GROUP BY DAY(date)"));
foreach($select_stats as $statics) {
//change our object to an array
$statics = array();
}
return View::make('admin.home.index')->with('stats', $select_stats)/*->with('count', $get_count)*/;
}
database model
View
var visitors = [
#foreach($stats as $stat)
['{{ date("d/m/Y", strtotime($stat->date)) }}', 55],
#endforeach
];
I want to get a stat like this:
But with the correct data from the database.
I want that I get the count of all IP's that visited my site on day 'x', and that for a month long.
So: on 2015-04-14 I got 20 visits, that is what I want to get, but looped in my template.
I hope you guys do understand me.
Kindest regards,

Categories