To add a line chart inside a table component in Filament PHP, you can use the following approach:
- Create a new Blade component that renders the line chart using Chart.js. Let's call it
LineChartComponent. This component will accept the necessary data to render the chart.
// app/View/Components/LineChartComponent.php
namespace App\View\Components;
use Illuminate\View\Component;
class LineChartComponent extends Component
{
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function render()
{
return view('components.line-chart');
}
}
- Create a Blade view file for the
LineChartComponentthat contains the necessary HTML and JavaScript code to render the line chart using Chart.js. You can customize this view file based on your specific chart requirements.
<!-- resources/views/components/line-chart.blade.php -->
<div>
<canvas id="line-chart-{{ $data['id'] }}"></canvas>
<script>
var ctx = document.getElementById('line-chart-{{ $data['id'] }}').getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
labels: {!! json_encode($data['labels']) !!},
datasets: [{
label: '{{ $data['label'] }}',
data: {!! json_encode($data['values']) !!},
backgroundColor: 'rgba(0, 123, 255, 0.5)',
borderColor: 'rgba(0, 123, 255, 1)',
borderWidth: 1
}]
},
options: {
// Customize chart options as needed
}
});
</script>
</div>
- Update your Filament table configuration to use the
LineChartComponentfor thekeyword_trendcolumn. Pass the necessary data to the component.
// app/Filament/Tables/YourTable.php
use App\View\Components\LineChartComponent;
use Filament\Tables\Columns\ViewColumn;
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('keyword')
->defaultPaginationPageOption(50)
->columns([
ViewColumn::make('keyword_trend')
->view('filament.tables.columns.keyword-trend')
->component(LineChartComponent::class, function ($record) {
return [
'id' => $record->id,
'label' => $record->keyword,
'labels' => $record->trendLabels,
'values' => $record->trendValues,
];
}),
]);
}
- In your
filament.tables.columns.keyword-trendBlade view file, include theLineChartComponentand pass the necessary data to it.
<!-- resources/views/filament/tables/columns/keyword-trend.blade.php -->
<x-line-chart :data="$column->componentProps" />
Make sure to adjust the data passed to the LineChartComponent based on your specific requirements.
This solution separates the chart rendering logic into a reusable component, which should help with performance and pagination issues.