Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Charts Laravel Package

consoletvs/charts

ConsoleTVs Charts is a Laravel/PHP package for building interactive charts from your data. Generate chart objects with a clean API, integrate with popular JS libraries, and render responsive visualizations in Blade views for dashboards, reports, and admin panels.

Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require consoletvs/charts

Publish the config file (if needed):

php artisan vendor:publish --provider="ConsoleTVs\Charts\ChartsServiceProvider"
  1. First Chart in Blade

    {!! Charts::create('users-chart', 'line')
        ->title('User Growth')
        ->elementLabel('Users')
        ->colors(['#4CAF50'])
        ->dataset('Users', [10, 20, 30, 40])
        ->responsive(true)
    !!}
    
  2. Quick Eloquent Integration

    $users = User::selectRaw('count(*) as count, created_at')
        ->whereYear('created_at', now()->year)
        ->groupBy('month(created_at)')
        ->get();
    
    {!! Charts::create('monthly-users', 'line')
        ->title('Monthly Users')
        ->elementLabel('Users')
        ->dataset('Users', $users->pluck('count')->toArray())
        ->labels($users->pluck('created_at')->toArray())
        ->responsive(true)
    !!}
    

Where to Look First

  • Config File: config/charts.php (for default settings like chart engines, paths, etc.)
  • Documentation: Focus on the Fluent API section for method chaining.
  • Chart Engines: Check supported drivers (e.g., chartjs, highcharts) in config/charts.php under engines.

Implementation Patterns

Common Workflows

1. Eloquent-Based Charts

// Grouped bar chart from Eloquent
$orders = Order::selectRaw('status, count(*) as total')
    ->groupBy('status')
    ->get();

{!! Charts::create('order-status', 'bar')
    ->title('Order Status Distribution')
    ->elementLabel('Orders')
    ->dataset('Status', $orders->pluck('total')->toArray())
    ->labels($orders->pluck('status')->toArray())
    ->colors(['#FF5733', '#33FF57', '#3357FF'])
    ->responsive(true)
!!}

2. Dynamic Data with Collections

$revenue = collect([
    ['month' => 'Jan', 'amount' => 1000],
    ['month' => 'Feb', 'amount' => 1500],
]);

{!! Charts::create('revenue-trend', 'line')
    ->title('Monthly Revenue')
    ->elementLabel('USD')
    ->dataset('Revenue', $revenue->pluck('amount')->toArray())
    ->labels($revenue->pluck('month')->toArray())
    ->options(['responsive' => true, 'maintainAspectRatio' => false])
!!}

3. Multi-Series Charts

$users = User::selectRaw('count(*) as users, gender')
    ->groupBy('gender')
    ->get();

$admins = Admin::selectRaw('count(*) as admins, gender')
    ->groupBy('gender')
    ->get();

{!! Charts::create('gender-distribution', 'pie')
    ->title('Gender Breakdown')
    ->type('doughnut')
    ->dataset('Users', $users->pluck('users')->toArray())
    ->dataset('Admins', $admins->pluck('admins')->toArray())
    ->labels(['Male', 'Female', 'Other'])
    ->colors(['#FF6384', '#36A2EB', '#FFCE56'])
!!}

4. Customizing with Options

{!! Charts::create('sales-overview', 'line')
    ->title('Sales Overview')
    ->options([
        'responsive' => true,
        'plugins' => [
            'legend' => ['position' => 'top'],
            'tooltip' => ['mode' => 'index'],
        ],
        'scales' => [
            'y' => ['beginAtZero' => false],
        ],
    ])
!!}

5. Reusable Chart Components

Create a Blade component (resources/views/components/chart.blade.php):

@props(['chartId', 'type', 'title', 'data'])

{!! Charts::create($chartId, $type)
    ->title($title)
    ->elementLabel('Value')
    ->dataset('Data', $data['values'])
    ->labels($data['labels'] ?? [])
    ->options($data['options'] ?? [])
    ->responsive(true)
!!}

Usage:

<x-chart
    chartId="revenue-chart"
    type="line"
    title="Revenue Trend"
    :data="[
        'values' => [100, 200, 300],
        'labels' => ['Q1', 'Q2', 'Q3'],
    ]"
/>

Integration Tips

Blade Directives

Use @chart directive for cleaner Blade syntax:

@chart('users-chart', 'line')
    ->title('User Growth')
    ->dataset('Users', [10, 20, 30])
@endchart

API Responses

Return charts directly from API routes (e.g., for SPAs):

return response()->json([
    'chart' => Charts::create('api-chart', 'bar')
        ->dataset('Data', [1, 2, 3])
        ->getData(),
]);

Caching Charts

Cache chart data or rendered HTML for performance:

// Cache the chart data for 1 hour
$chartData = Cache::remember('chart-users', 3600, function () {
    return Charts::create('cached-chart', 'line')
        ->dataset('Users', User::count())
        ->getData();
});

Testing Charts

Mock chart data in tests:

$mockChart = Mockery::mock('overload', Charts::class);
$mockChart->shouldReceive('create')
    ->andReturnSelf();
$mockChart->shouldReceive('getData')
    ->andReturn(['data' => 'mocked']);

Gotchas and Tips

Pitfalls

1. Driver Mismatches

  • Issue: Charts may render incorrectly if the configured driver (e.g., chartjs) doesn’t match the expected output.
  • Fix: Verify the default engine in config/charts.php and ensure the driver is installed (e.g., npm install chart.js for chartjs).
  • Debug: Check the rendered HTML for missing scripts or console errors.

2. Label/Data Mismatch

  • Issue: Charts may throw errors if labels() and dataset lengths don’t match.
  • Fix: Always ensure ->labels() and dataset arrays are the same length.
  • Example:
    // Wrong: Labels and data lengths differ
    ->labels(['Jan', 'Feb']) // 2 items
    ->dataset('Sales', [100, 200, 300]) // 3 items
    
    // Correct: Matching lengths
    ->labels(['Jan', 'Feb', 'Mar'])
    ->dataset('Sales', [100, 200, 300])
    

3. Responsive Issues

  • Issue: Charts may not resize properly in containers with fixed heights.
  • Fix: Explicitly set ->responsive(true) and ensure the container has a defined height (e.g., style="height: 400px").

4. Eloquent Raw Queries

  • Issue: Complex selectRaw queries might return unexpected data types (e.g., Carbon objects in labels).
  • Fix: Cast data explicitly:
    ->labels($users->pluck('created_at')->map(fn($date) => $date->format('Y-m'))->toArray())
    

5. Overwriting Config

  • Issue: Custom chart engines or options may be overridden by published config.
  • Fix: Extend the config file instead of replacing it:
    'engines' => [
        'chartjs' => [
            'path' => resource_path('js/chart.js'),
            // Custom options
        ],
    ],
    

Debugging Tips

1. Inspect Raw Data

Use ->getData() to debug the chart configuration before rendering:

$chart = Charts::create('debug-chart', 'line')
    ->dataset('Data', [1, 2, 3]);
dd($chart->getData()); // Inspect the raw config

2. Check Rendered HTML

View the source of the rendered chart to verify scripts and styles are loaded:

<!-- Look for these in the output -->
<script src="/vendor/chartjs/chart.min.js"></script>
<canvas id="users-chart" ...></canvas>
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport