Charts (amCharts)
App\Component\Chart\Chart wraps amCharts 5 as a CG component. The principle is the same as for the whole framework: every capability is an attribute.
- The PHP fluent API only builds a spec, output as the root's
data-chart(JSON) anddata-chart-*attributes. - The front end only reads attributes, so renderBlade fragments,
@linkermounts and state namespaces need no extra integration. - The chart engine (about 80 KB gzipped) is loaded dynamically the first time a chart scrolls into view.
- The default driver is amCharts 5; Chart.js is built in, and you can add your own.
Minimal example
@php
use App\Component\Chart\Chart;
@endphp
{{ Chart::make('sales')
->title('Revenue', 'Last 90 days')
->line()->dateField('date')
->series(['revenue' => 'Revenue', 'orders' => 'Orders'])
->data($rows) }}$rows can be an array, Collection, Eloquent collection, iterable or Closure:
$rows = [
['date' => '2026-09-01', 'revenue' => 1200, 'orders' => 31],
['date' => '2026-09-02', 'revenue' => 1530, 'orders' => 40],
];Common capabilities
use App\Component\Chart\ChartSeries;
Chart::make('budget')
->title('Monthly budget', 'Last two years')
->dateField('month', 'month')
->time(['6M', '1Y', 'all'], ['month']) // range buttons + granularity (computed locally, no server call)
->series([
ChartSeries::make('budget', 'Budget')->type('column')->color('#94a3b8'),
ChartSeries::make('actual', 'Actual')->type('column')->color('#2563eb'),
ChartSeries::make('rate', 'Execution rate')->type('line')->y2()->smooth()->color('#dc2626'),
])
->axis(1, 'Amount', min: 0)->axis(2, 'Rate')
->numberFormat('#,###')
->markLine(200000, 'Target', '#dc2626')
->markPeriod('2026-06-01', '2026-07-31', 'Peak season')
->cursor('multi')
->zoom(x: true, mode: 'select')
->scrollbar()
->exportable(['png', 'pdf', 'csv', 'xlsx', 'html'], 'budget')
->font('Noto Sans TC', 'notosans-tc') // embed a font so PDFs can render CJK text
->emptyText('No data for this period', 'Try another date range')
->data($rows);| Need | API |
|---|---|
| Chart type | line(), ->type('column') on a series, Chart::gantt() |
| Time axis and ranges | dateField(), time() |
| Second Y axis | ChartSeries::y2() + axis(2, …) |
| Reference lines / bands | markLine() markBand() markDate() markPeriod() |
| Cursor | `cursor('none |
| Zoom | zoom() scrollbar() |
| Export | exportable([...]), including self-contained interactive html |
| Empty data | emptyText(), cursorWhenEmpty() |
| Renderer | renderer('canvas') (many data points) / svg by default |
Loading data from Linker
Mount the chart on a Linker component and name the loading method with source():
{{ Chart::make('sales')
->stateless('sales-chart') // or ->linker('alias') (Stateful)
->source('load', ['range' => '3M'])
->refresh(30) // re-fetch every 30 s; paused while the tab is hidden
->line()->dateField('date')
->series(['revenue' => 'Revenue']) }}class SalesChartLinker extends LinkerComponent
{
public static string $alias = 'sales-chart';
public static function mode(): LinkerMode
{
return LinkerMode::Stateless;
}
#[Computable(cache: true, seconds: 30)]
#[Validate(['range' => 'nullable|string|in:1M,3M,1Y,all'])]
public function load(array $args): LinkerResponse
{
return $this->ok(['rows' => Sales::daily($args['range'] ?? '3M')]);
}
}The returned data decides how the chart updates:
| Return | Effect |
|---|---|
['rows' => [...]] | Replace all data |
['append' => [$point]] | Append a point; with ->window(200) it becomes a rolling window |
['zoom' => ['start' => .2, 'end' => .8]] | Sync zoom to that range |
Synced zoom across charts
Chart::make('revenue')->syncZoom('dash')->...;
Chart::make('orders')->syncZoom('dash')->...;Charts on the same page, and in other tabs of the same browser, stay in sync. syncZoom('dash', call: 'saveZoom') also saves the zoom range on the server through Linker.
Inside renderBlade fragments
Charts listen for cg:rendered: they initialize after a fragment is inserted and are disposed when replaced. When filters change, re-render the whole block with render.fragment; no extra chart API is needed.
Switching drivers
Chart::make('sales')->driver('chartjs')->line()->...;The same spec switches chart libraries with one line. Capabilities a driver lacks are gracefully degraded with a console warning (for example, dropping Y2). An unsupported chart type shows a message instead of drawing the wrong chart. The site-wide default is chart.driver in config/cg-components.php (CG_CHART_DRIVER).
Native amCharts escape hatches
| Need | Use |
|---|---|
| A full amCharts JSON config | rawConfig([...]) |
| Merge native settings into the generated objects | amchart(['chart' => [...], 'series' => ['revenue' => [...]]]) |
| Customization that needs code | ->hook('name') + registerChartHook('name', ({ chart, series, root, … }) => …) on the front end |
A hook can only reference a name registered on the front end. The server can't send code, the same principle as the action table.
Plain HTML works too
The front end only reads attributes, so you can skip the PHP component: put the JSON spec in data-chart on the root and override individual settings with discrete data-chart-* attributes.
<div data-chart='@json($chart->spec())'
data-chart-cursor="cross"
data-chart-zoom="x wheel"
data-chart-renderer="canvas"></div>
{{-- Toolbar buttons: range and export --}}
<button data-chart-range="3M">Last 3 months</button>
<button data-chart-export="png">Export PNG</button>The JSON spec format follows the output of Chart::spec() (parsed in resources/js/chart/spec.js). Common discrete attributes: data-chart-type, -cursor, -zoom, -driver, -source, -refresh, -sync, -renderer, -legend, -axis-tooltips.
Security
Colors accept only #hex / rgb(); field, group and method names go through allow-list regexes; embedded data is encoded with JSON_HEX_*; inconsistent combinations (no series, refresh without source, bar with Y2…) throw at render time.
License
amCharts 5 is free by default (the amCharts logo appears in the bottom-left corner). For a commercial license, follow amCharts' terms.
More details (driver contract, extensions, testing tools) in the repo's docs/Component/chart.md.