Installation Add the bundle to your Laravel project via Composer:
composer require anh/content-charts-bundle
Register the bundle in config/bundles.php:
Anh\ContentChartsBundle\AnhContentChartsBundle::class => ['all' => true],
Publish Assets Run the following command to publish the bundle’s assets (if applicable):
php artisan vendor:publish --provider="Anh\ContentChartsBundle\AnhContentChartsBundle" --tag=public
First Use Case
Use the bundle to generate a simple chart for a content entity (e.g., Article). Example in a controller:
use Anh\ContentChartsBundle\Chart\ChartBuilder;
public function showChart()
{
$chart = (new ChartBuilder())
->setEntity('App\Entity\Article')
->setType('line') // or 'bar', 'pie', etc.
->setField('views') // Field to chart (e.g., views count)
->setTimeRange('month') // 'day', 'week', 'month', 'year'
->build();
return view('charts.show', ['chart' => $chart]);
}
Blade Integration Render the chart in a Blade template:
{!! $chart->render() !!}
Dynamic Chart Generation
Use the ChartBuilder to dynamically generate charts based on user input (e.g., dashboard filters):
$chart = (new ChartBuilder())
->setEntity($entityClass)
->setType($request->input('type', 'line'))
->setField($request->input('field', 'views'))
->setTimeRange($request->input('range', 'month'))
->setGroupBy($request->input('group_by', 'created_at'))
->build();
Reusable Chart Components Create a service to encapsulate chart logic for reuse across controllers:
namespace App\Services;
use Anh\ContentChartsBundle\Chart\ChartBuilder;
class ChartService {
public function buildContentChart(array $config) {
$builder = new ChartBuilder();
foreach ($config as $method => $value) {
if (method_exists($builder, $method)) {
$builder->$method($value);
}
}
return $builder->build();
}
}
Integration with Content Bundle
Leverage the dependency on anh/content-bundle to fetch content entities and their metadata:
$chart = (new ChartBuilder())
->setEntity('App\Entity\Article')
->setContentBundleService($this->contentBundleService) // Inject if needed
->build();
API Responses Return chart data as JSON for API endpoints:
return response()->json($chart->getData());
Custom Chart Types Extend the bundle to support additional chart types (e.g., area, radar) by creating a custom chart class:
namespace App\Charts;
use Anh\ContentChartsBundle\Chart\AbstractChart;
class CustomChart extends AbstractChart {
protected $type = 'custom';
// Override render logic
}
Localization Customize labels and tooltips for non-English content:
$chart = (new ChartBuilder())
->setLabels(['views' => 'Page Views', 'created_at' => 'Publication Date'])
->build();
Caching Cache chart data to improve performance for frequently accessed charts:
$chartData = Cache::remember("chart_{$entity}_{$field}_{$range}", now()->addHours(1), function() use ($builder) {
return $builder->build()->getData();
});
Event Listeners Trigger events when charts are generated (e.g., logging, analytics):
// In a service provider
$this->app->booted(function() {
AnhContentChartsBundle::addListener('chart.generated', function($chart) {
// Log or process chart data
});
});
Entity Field Validation
Ensure the setField() method points to a valid field in your entity. Invalid fields will throw exceptions or return empty data.
Fix: Validate fields before building the chart:
if (!$entity->hasField($field)) {
throw new \InvalidArgumentException("Field '$field' does not exist on entity.");
}
Time Range Handling
The setTimeRange() method assumes fields like created_at are DateTime or DateTimeImmutable. Custom date fields may require formatting.
Fix: Use setDateFormat() to specify custom date formats:
$chart = (new ChartBuilder())
->setDateFormat('Y-m-d H:i:s')
->build();
Dependency on anh/content-bundle
The bundle relies on anh/content-bundle for entity metadata. Ensure this bundle is properly installed and configured.
Fix: Verify anh/content-bundle is registered in config/bundles.php and entities are annotated correctly.
Asset Loading If charts fail to render, check that assets (JS/CSS) are published and loaded in your layout:
@vite(['resources/css/charts.css', 'resources/js/charts.js'])
Empty Charts If a chart renders but shows no data:
JavaScript Errors Inspect the browser console for errors related to the chart library (e.g., Chart.js). Common causes:
$data = $chart->getData();
dd($data); // Debug the output
Performance Issues Large datasets may cause slow rendering. Optimize with:
created_at).$chart = (new ChartBuilder())
->setQueryBuilder(function($qb) {
return $qb->select('DATE(created_at) as date', 'SUM(views) as total_views')
->groupBy('date');
})
->build();
Custom Chart Builders
Extend ChartBuilder to add domain-specific logic:
namespace App\Charts;
use Anh\ContentChartsBundle\Chart\ChartBuilder;
class ArticleChartBuilder extends ChartBuilder {
public function setArticleType($type) {
$this->options['article_type'] = $type;
return $this;
}
}
Query Customization Override the default query builder to add joins or complex logic:
$chart = (new ChartBuilder())
->setQueryBuilder(function($qb) {
$qb->join('article_tags', 't', 't.article_id = a.id')
->where('t.tag', 'featured');
return $qb;
})
->build();
Post-Processing Data Modify chart data after generation (e.g., formatting values):
$chart = (new ChartBuilder())->build();
$chart->setData(array_map(function($item) {
$item['views'] = number_format($item['views']);
return $item;
}, $chart->getData()));
Theme Support Add support for custom themes (e.g., dark mode) by extending the renderer:
$chart = (new ChartBuilder())
->setTheme('dark')
->build();
How can I help you explore Laravel packages today?