Please Help me i need pass this sql lines to a laravel syxtax to use
on customizable charts
Im using
https://github.com/ConsoleTVs/Charts
Sql Syntax:
SELECT
SUM(CASE WHEN status like 'Por Despachar' THEN 1 ELSE 0 END) AS Por_Despachar
,SUM(CASE WHEN status like 'Planificado' THEN 1 ELSE 0 END) AS Planificado
,SUM(CASE WHEN status like 'Despachado' THEN 1 ELSE 0 END) AS Despachado
FROM presupuesto
i want to add this parameter on interactive chart like this
enter image description here
This is my Controller:
<?php
namespace sisVentas\Http\Controllers;
use Illuminate\Http\Request;
use sisVentas\User;
use sisVentas\Http\Requests;
use Charts;
class EstadisticaController extends Controller
{
//
public function index()
{
$data = \DB::select("
SELECT
SUM(CASE WHEN status like 'Por Despachar' THEN 1 ELSE 0 END) AS Por_Despachar
,SUM(CASE WHEN status like 'Planificado' THEN 1 ELSE 0 END) AS Planificado
,SUM(CASE WHEN status like 'Despachado' THEN 1 ELSE 0 END) AS Despachado
FROM presupuesto
");
$chart = Charts::create('pie', 'highcharts')
// Setup the chart settings
->title("Resumen de Presupuestos Realizados")
// A dimension of 0 means it will take 100% of the space
// This defines a preset of colors already done:)
// You could always set them manually
// Setup the diferent datasets (this is a multi chart)
->labels(['Por Despachar', 'Despachado', 'Planificado'])
->values([65,10,20])
->dimensions(1000,500)
->responsive(false);
return dd($chart, $data);
}
}
Chart {#324 ▼
+id: null
+customId: null
+type: "pie"
+library: "highcharts"
+title: "Resumen de Presupuestos Realizados"
+element_label: "Element"
+labels: array:3 [▼
0 => "Por Despachar"
1 => "Despachado"
2 => "Planificado"
]
+values: array:3 [▼
0 => 65
1 => 10
2 => 20
]
+colors: []
+responsive: false
+gauge_style: "left"
+view: null
+region: "world"
#suffix: ""
+container: ""
+credits: false
+loader: true
+loader_duration: 500
+loader_color: "#000000"
+background_color: "inherit"
+template: "material"
+one_color: false
+legend: true
+x_axis_title: false
+y_axis_title: null
+"height": 500
+"width": 1000
}
array:1 [▼
0 => {#330 ▼
+"por_despachar": "3"
+"planificado": "1"
+"despachado": "0"
}
]
Maybe not direct answer but should be helpful
When you have any SQL query that is hard / impossible to convert into eloquent, just use DB facade.
$data = \DB::select("
SELECT
SUM(CASE WHEN status like 'Por Despachar' THEN 1 ELSE 0 END) AS Por_Despachar
,SUM(CASE WHEN status like 'Planificado' THEN 1 ELSE 0 END) AS Planificado
,SUM(CASE WHEN status like 'Despachado' THEN 1 ELSE 0 END) AS Despachado
FROM presupuesto
");
dd($data);
$chart = Charts::database($data, 'pie', 'highcharts')
->title('Amount subscribers')
->labels([Por_Despachar, Planificado, Despachado])
->values([$data[0]->Por_Despachar, $data[1]->Planificado, $data[2]->Despachado])
->dimensions(1000,500)
->responsive(true);
Related
I am trying to get data between "Start" and "End" dates from database which is working fine and query giving me the result, Say
Start = 09-02-2022.
End = 10-03-2022.
Database values start = "01-03-2022 to 09-03-2022" so i am getting result from date say 16-02 to 01-03.
But i want result should start with 09-02 and end with 10-03. If value is not present in database then it should give as "0"
Check attached Image for reference.
Code for Getting dates for last 30 days -
$getalldates = array();
for($d = (Carbon::today()->subDays(30)); $d->lte(carbon::today()); $d->addDay())
{ $getalldates[] = $d->format('Y-m-d');}
Code for Getting data from database
$rahul = Buffalomilkrecord::select(DB::raw('date'), DB::raw('sum(totalmilk) as totalmilk, DATE_FORMAT(date,"%d") as "daykey"'))
->whereBetween('date', [$olddate, $todaydate] )
->groupBy(DB::raw('date'))
->orderBy('date','asc')
->get()->pluck('date')->toArray();
Thanks in Advance.
This is what i tried
$result = array();
foreach($getalldates as $date){
$totalmilk= Buffalomilkrecord::select(DB::raw('sum(totalmilk) as totalmilk'))->whereDate('date',$date)->pluck('totalmilk');
if($totalmilk){
$result[] = array($date =>$totalmilk);
} else {
$result[] = array($date =>0);
}
}
I am expecting
This is my output 0 => array:1 [▼ "2022-02-09" => Illuminate\Support\Collection {#348 ▼ #items: array:1 [▼ 0 => null ] }
and i am expecting "2022-02-09" = "0"
Check Image
I am trying to get data for each id using foreach. But when code run it get only data for 1 ID.. Following is the code
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->get('buffaloID')- >pluck('buffaloID')->toArray();
foreach ($buffalidforavgmilk as $id) {
$milkperid = Buffalomilkrecord::where('buffaloID', $id)->pluck('buffaloID')->toArray();
dd([$buffalidforavgmilk,$milkperid]);
}
Output
array:2 [▼
0 => array:4 [▼
0 => "Buffalo-01"
1 => "Buffalo-02"
2 => "Buffalo-03"
3 => "Buffalo-04"
]
1 => array:5 [▼
0 => "Buffalo-01"
1 => "Buffalo-01"
2 => "Buffalo-01"
3 => "Buffalo-01"
4 => "Buffalo-01"
]
]
Here Loop giving only 1 ID where as required array for all 4 ID
( for Test, i try to get only buffaloID)
Thanks in Advance
dd interrupts execution. If you wanted to dump every result and then stop execution, you should have used dump instead
foreach ($buffalidforavgmilk as $id) {
$milkperid = Buffalomilkrecord::where('buffaloID', $id)->pluck('buffaloID')->toArray();
dump([$buffalidforavgmilk,$milkperid]);
}
dd('Done');
This is not ideal though. You are making a query in each iteration of the loop.
One way you could remove the foreach is to change your query to use whereIn.
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->pluck('buffaloID')->toArray();
$milkperids = Buffalomilkrecord::whereIn('buffaloID', $buffalidforavgmilk)->pluck('buffaloID')->toArray();
Describe the bug
I'm trying to generate a chart, however when I pass the parameter "filter" to SQL Builder, more specifically the file "TotalRecordsController" assembles the query as if I were using MySQL, instead of mounting it for PostgreSQL.
Laravel: 8.40
PHP: 7.4
PostgreSQL: 12
Nova: 3.30
ChartJS: 0.3.5
Linux Mint
Chrome
My Code:
public function cards(Request $request)
{
$process_statuses= [
["label"=>"INITIAL" ,"color" => "#007BFF"],
['label'=>'CONVERTED' ,'color' => '#28A645'],
['label'=>'ERROR' ,'color' => '#DC3544'],
['label'=>'WAITING_TO_ERICH' ,'color' => '#17A2B8'],
['label'=>'WAITING_TO_CONVERT','color' => '#17A2B8']
];
$series = [];
foreach ($process_statuses as $status){
$new_serie = [
'label' => $status['label'],
'filter'=>[
'key'=>'process_status',
'value'=>$status['label']
],
'barPercentage' => 0.5,
'backgroundColor' => $status['color'],
];
$series = [...$series,$new_serie];
}
return [
(new BarChart())
->title('Today Status')
//->model(\App\Models\GoogleOfflineConversion::class)
->model('\App\Models\FacebookOfflineConversion')
->series($series)
->options([
'btnRefresh'=>true,
'uom' => 'hour',
])->width('full'),
];
}
Error:
SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "'INITIAL'"
LINE 1: ... process_status = 'INITIAL' then 1 else 0 end) as 'INITIAL',...
^ (SQL: select HOUR(facebook_offline_conversions.created_at) AS cat, HOUR(facebook_offline_conversions.created_at) AS catorder, sum(1) counted, SUM(CASE WHEN process_status = 'INITIAL' then 1 else 0 end) as 'INITIAL', SUM(CASE WHEN process_status = 'CONVERTED' then 1 else 0 end) as 'CONVERTED', SUM(CASE WHEN process_status = 'ERROR' then 1 else 0 end) as 'ERROR', SUM(CASE WHEN process_status = 'WAITING_TO_ERICH' then 1 else 0 end) as 'WAITING_TO_ERICH', SUM(CASE WHEN process_status = 'WAITING_TO_CONVERT' then 1 else 0 end) as 'WAITING_TO_CONVERT' from "facebook_offline_conversions" where facebook_offline_conversions.created_at >= 2021-10-28 00:00:00 group by "catorder", "cat" order by "catorder" asc)
Migration of the my database:
Schema::create('facebook_offline_conversions', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('company_id')->nullable();
$table->integer('refer_site_id')->nullable();
$table->foreignUuid('site_id')->nullable();
$table->foreignUuid('facebook_ads_site_credential_id')->nullable();
$table->string('crm_order_id')->nullable();
$table->string('fbc')->nullable();
$table->longText('document_number')->nullable();
$table->longText('email')->nullable();
$table->longText('phone_number')->nullable();
$table->float('value')->nullable();
$table->string('currency')->nullable();
$table->longText('city')->nullable();
$table->longText('state')->nullable();
$table->longText('zip_code')->nullable();
$table->longText('country')->nullable();
$table->timestamp('conversion_time')->nullable();
$table->longText('ip_address')->nullable();
$table->longText('browser')->nullable();
$table->string('process_status')->nullable();
$table->integer('tries')->nullable();
$table->boolean('approximated')->default(false);
$table->json('conversion_response')->nullable();
$table->timestamps();
});
I'm resolving this problem. The solution is to change the file "src/api/TotalRecordsController" inside the folder "~/vendor/coroowicaksono/chart-js-integration" so that it suits PostgreSQL.
can I pluck the 3 arrays like these because only two are shown?
$data = Receipt::select(DB::raw("DATE(created_on) as date"), DB::raw("sum(case when type = 'Receipt' then 1 else 0 end) AS cnt_receipt"), DB::raw("sum(case when type = 'Invoice' then 1 else 0 end) AS cnt_invoice"))
->groupBy('date')
->pluck('cnt_receipt', 'cnt_invoice', 'date')->all();
If not, how can I able show those 3 arrays?
I want the output something like this
date cnt_receipt cnt_invoice
2021-01-01 5 6
2021-01-02 8 5
2021-01-03 10 9
2021-01-04 11 9
I need to get those data as arrays because the chart js code need array_keys and array_values
$chart= new Chart;
$chart->labels = (array_keys($data));
$chart->r_dataset = (array_values($data));
$chart->i_dataset = (array_values($data));
Chart Class
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Chart extends Model
{
//
}
What you need to use is reduce here, a bit of a hacky way, but it will work.
$data = Receipt::select(DB::raw("DATE(created_on) as date, sum(case when type = 'Receipt' then 1 else 0 end) AS cnt_receipt, sum(case when type = 'Invoice' then 1 else 0 end) AS cnt_invoice"))
->groupBy('date')->all();
Then;
$chartInitial = new Chart();
$chartInitial->labels = [];
$chartInitial->r_dataset = [];
$chartInitial->i_dataset = [];
$chart = $data->reduce(function($obj, $row){
$obj->labels[] = $row->date;
$obj->r_dataset[] = $row->cnt_receipt;
$obj->i_dataset[] = $row->cnt_invoice;
return $obj;
}, $chartInitial);
It'll push all the row data into their respective arrays in that Chart object.
This the data when user submit the form :
POST Data
_token
"JNDt8WC6kVbvrSdFTKSGnHsfzTuIsbthslf5Gqjs"
invoice_number
"15"
dateofbill
"2019-04-19"
customer_name
"praveen kumar tiwari"
customer_mobile
"8924001750"
sno
array:3 [▼
0 => "1"
1 => "2"
2 => "3"
]
item_name
array:3 [▼
0 => "jeans"
1 => "shirt"
2 => "lower"
]
qty
array:3 [▼
0 => "2"
1 => "3"
2 => "2"
]
price
array:3 [▼
0 => "20000"
1 => "232"
2 => "12"
]
gst
array:3 [▼
0 => "1200"
1 => "22"
2 => "12"
]
discount
array:3 [▼
0 => "100"
1 => "23"
2 => "12"
]
textarea
""
i cannot be able to store this data into a table. i am trying with for loop but getting an error "Undefined offset: 3".
Code inside the controller
for($i=0;$i<=count($request['sno']);$i++)
{
$invoice = new Invoice;
$invoice->sendbill_id=$bill->id;
$invoice->sno=$request['sno'][$i];
$invoice->item_name=$request->item_name[$i];
$invoice->qty=$request->qty[$i];
$invoice->price=$request->price[$i];
$invoice->gst=$request->gst[$i];
$invoice->discount=$request->discount[$i];
$invoice->save();
}
i want to store these 3 values comming in the array form (sno,item_name,qty,price,gst,discount) in 3 diffrent rows
You should try to use laravel eloquent to save it. Here is some example that you can check it out. Laravel : Many to many insertion
The problem you have is indeed your loop: for($i=0;$i<=count($request['sno']);$i++).
To be specific it is this right here <=:
$i<=count()
^^
Take a look at your array:
[
0 => "1"
1 => "2"
2 => "3"
]
You got a total of 3 objects. count($request['sno']) will therefore return 3 since the count() function does not start counting at 0!
However, calling an index (e.g. $request['sno'][1]) will not return the first object (0 => "1") but the second (1 => "2"). I think you see where I am going.
Since the loop will go on until $i equals 3 the loop will be completed 4 times. At the last time (where $i == 3) you try to get the 4th item out of your array which does not exist so an error message pops up: Undefined offset: 3.
To solve this just change this
$i<=count()
^^
to <. The loop will only be executed if $i is still smaller then 3. This is the case if $i == 2. No error message will pop up.
I do not want to attack or hurt you in any way, but it seems to me that you are relatively new to PHP. Of course, that's not a shame, but I'm wondering if a huge framework like Laravel is right for you. First the basics, then comes the advanced.
But that's only as a small comment and tip from me.