mohsen-mhm/laravel-image-charts
Installation:
composer require mohsen-mhm/laravel-image-charts
php artisan vendor:publish --provider="MohsenMhm\LaravelImageCharts\Providers\ImageChartsServiceProvider" --tag="config"
Verify config/image-charts.php exists.
First Use Case: Generate a simple bar chart URL via the facade:
use MohsenMhm\LaravelImageCharts\Facades\ImageCharts;
$url = ImageCharts::barChart()
->setTitle('Monthly Sales')
->addDataPoint(100)
->addDataPoint(200)
->addDataPoint(150)
->render();
Access the URL in your browser or embed it in a view.
MohsenMhm\LaravelImageCharts\Facades\ImageCharts (primary entry point).config/image-charts.php (customize defaults like colors, dimensions, or storage paths).lineChart(), pieChart(), doughnutChart(), etc., in the facade.Dynamic Chart Generation:
// Generate a chart dynamically from a database query
$users = User::selectRaw('COUNT(*) as count, MONTH(created_at) as month')
->groupBy('month')
->get();
$url = ImageCharts::lineChart()
->setTitle('User Signups by Month')
->setXAxisLabels(['Jan', 'Feb', 'Mar', 'Apr'])
->addDataSeries($users->pluck('count')->toArray())
->render();
Reusable Chart Logic: Create a service class to encapsulate chart generation:
class SalesChartService {
public function generateMonthlySalesChart(int $year) {
$data = Sales::whereYear('created_at', $year)
->selectRaw('SUM(amount) as total, MONTH(created_at) as month')
->groupBy('month')
->get();
return ImageCharts::barChart()
->setTitle("Sales for $year")
->setXAxisLabels(['Jan', 'Feb', ..., 'Dec'])
->addDataSeries($data->pluck('total')->toArray())
->render();
}
}
Caching Chart Images:
Store generated charts in storage/app/public/charts (default) and serve via:
$url = ImageCharts::pieChart()
->setTitle('Project Status')
->addDataPoint(30, 'In Progress')
->addDataPoint(70, 'Completed')
->setImagePath('custom/path') // Override default storage path
->render();
Link to the image in your views:
<img src="{{ asset('storage/charts/custom/path.png') }}" alt="Chart">
Integration with Blade:
@php
$chartUrl = ImageCharts::doughnutChart()
->setTitle('User Roles')
->addDataPoint(50, 'Admin')
->addDataPoint(30, 'Editor')
->addDataPoint(20, 'Viewer')
->render();
@endphp
<img src="{{ $chartUrl }}" class="img-fluid">
API Responses: Return chart URLs in JSON responses:
return response()->json([
'chart_url' => ImageCharts::lineChart()
->setTitle('API Requests')
->addDataPoint(150)
->addDataPoint(200)
->addDataPoint(180)
->render(),
]);
Custom Themes: Override default colors via config or dynamically:
ImageCharts::barChart()
->setBgColor('#1a1a2e')
->setDatasetBgColor('#FF6B6B')
->setDatasetBorderColor('#FF8E8E')
->addDataPoint(100);
Real-Time Updates: Use the package in combination with Laravel Echo/Pusher to update charts dynamically:
// Frontend: Listen for chart updates and reload the image
Echo.channel('chart-updates')
.listen('ChartUpdated', (data) => {
const img = document.getElementById('dynamic-chart');
img.src = data.chartUrl;
});
Multi-Series Charts:
$url = ImageCharts::lineChart()
->setTitle('Multi-Series Example')
->addDataSeries([10, 20, 15], 'Series 1', '#FF6384')
->addDataSeries([5, 15, 10], 'Series 2', '#36A2EB')
->render();
Storage Permissions:
Ensure the storage/app/public/charts directory is writable:
mkdir -p storage/app/public/charts && chmod -R 775 storage/app/public/charts
Fix: Manually set permissions or use Laravel’s storage:link:
php artisan storage:link
CORS Issues:
If accessing charts via AJAX or cross-domain, ensure your server allows requests to the chart URL (e.g., image-charts.com). For self-hosted charts, configure CORS headers.
Memory Limits:
Complex charts with high-resolution settings may hit PHP’s memory limit. Adjust memory_limit in php.ini or simplify chart data:
// Instead of:
ImageCharts::lineChart()->setWidth(5000)->setHeight(3000)...
// Use:
ImageCharts::lineChart()->setWidth(1200)->setHeight(800)...
Cache Invalidation: Changes to chart logic won’t reflect immediately if the image is cached. Clear the cache or use unique filenames:
ImageCharts::lineChart()
->setImagePath("charts/{$year}-{$month}.png") // Unique path
->render();
Deprecated Chart.js Version:
The package uses Chart.js 2.8.0 (as per base_url). If you need newer features, consider forking the package or using a different library.
Inspect Generated HTML: View the rendered chart URL in your browser to debug issues (e.g., missing data labels, misaligned axes). Use browser dev tools to inspect the image.
Log Configuration: Add debug logs to verify config values:
\Log::info('Image Charts Config:', [
'base_url' => config('image-charts.base_url'),
'width' => config('image-charts.default_width'),
]);
Test with Minimal Data: Start with 2-3 data points to isolate issues:
ImageCharts::barChart()
->addDataPoint(10)
->addDataPoint(20)
->render();
Check for Typos:
Method names are case-sensitive (e.g., setTitle() vs set_title()). Refer to the source code.
Custom Chart Types:
Extend the facade or create a new chart class by leveraging the underlying Chart class:
use MohsenMhm\LaravelImageCharts\Chart;
class CustomChart extends Chart {
public function radarChart() {
$this->type = 'radar';
return $this;
}
}
Register the new class in the service provider.
Add Interactive Elements:
Use the setOptions() method to pass Chart.js options:
ImageCharts::lineChart()
->setOptions([
'responsive' => true,
'plugins' => [
'legend' => ['position' => 'top'],
],
])
->addDataPoint(100);
Local Hosting:
Override base_url in config to use a locally hosted Chart.js:
'base_url' => asset('vendor/chart.js/2.8.0'),
Ensure Chart.js is available in your public folder.
Event Listeners: Hook into chart generation to log or modify data:
ImageCharts::addDataPoint(100)->then(function ($chart) {
\Log::info('Chart generated with data:', $chart->getData());
});
Testing: Mock the facade in PHPUnit tests:
$this->mock(MohsenMhm\LaravelImageCharts\Facades\ImageCharts::class)
->shouldReceive('lineChart')
->andReturnSelf()
->shouldReceive('
How can I help you explore Laravel packages today?