Good day, I need your assistance/guidance in creating a stacked bar chart using Chartjs in Laravel Filament. I have a tabled named 'Tasks' that has a relation with 'Clients' table. The fields for each table are as follows
Tasks
- ID
- title
- notes
- priority
- status
- type
- owner_id
- client_id
- created_at
- updated_at
Clients
- id
- client_name
- city
I want to create a stacked bar chart that will show all tasks per client grouped by their priority. I the following code snippets
- Getting all Tasks Per Client and Grouping By client_name and priority
$data = Tasks::select('clients.client_name as client_name', 'tasks.priority', DB::raw('COUNT(tasks.id) as task_count'))
->join('clients', 'tasks.client_id', '=', 'clients.id')
->groupBy('clients.client_name', 'tasks.priority')
->orderBy('clients.client_name')
->orderBy('tasks.priority')
->get();
- Preparing The Labels For Chart
// Prepare labels array
$labels = array_keys(reset($data));
- Preparing the datasets
// Prepare datasets array
$datasets = [];
foreach ($data as $client => $priorities) {
$dataset = [
'label' => $client,
'backgroundColor' => [
'rgba(255, 99, 132, 0.8)',
'rgba(54, 162, 235, 0.8)',
'rgba(255, 206, 86, 0.8)',
'rgba(75, 192, 192, 0.8)'
],
'data' => array_values($priorities),
];
$datasets[] = $dataset;
}
- Returning the Chart in Filament
return [
'datasets' => $datasets,
'labels' => $labels
];
- The whole code
<?php
namespace App\Filament\Widgets;
use App\Models\Tasks;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\DB;
class TasksByPriority extends ChartWidget
{
protected static ?string $heading = 'Tasks By Priority';
public function getDescription(): ?string
{
return 'Summary of tasks created by priority';
}
protected static ?string $maxHeight = '300px';
protected static ?string $pollingInterval = null;
protected function getData(): array
{
$data = Tasks::select('clients.client_name as client_name', 'tasks.priority', DB::raw('COUNT(tasks.id) as task_count'))
->join('clients', 'tasks.client_id', '=', 'clients.id')
->groupBy('clients.client_name', 'tasks.priority')
->orderBy('clients.client_name')
->orderBy('tasks.priority')
->get();
// Prepare labels array
$labels = array_keys(reset($data));
// Prepare datasets array
$datasets = [];
foreach ($data as $client => $priorities) {
$dataset = [
'label' => $client,
'backgroundColor' => [
'rgba(255, 99, 132, 0.8)',
'rgba(54, 162, 235, 0.8)',
'rgba(255, 206, 86, 0.8)',
'rgba(75, 192, 192, 0.8)'
],
'data' => array_values($priorities),
];
$datasets[] = $dataset;
}
return [
'datasets' => $datasets,
'labels' => $labels
];
}
protected function getType(): string
{
return 'bar';
}
}


