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

Svg Graph Bundle Laravel Package

creative-web-solution/svg-graph-bundle

Laravel bundle for generating SVG-based graphs and charts. Provides helpers to build and render scalable, lightweight visuals in your app, suitable for dashboards and reports, with customizable output for embedding in views or exports.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require creative-web-solution/svg-graph-bundle
    

    Register the bundle in config/app.php under providers:

    CreativeWebSolution\SvgGraphBundle\SvgGraphBundle::class,
    
  2. Basic Configuration Publish the default config (if needed):

    php artisan vendor:publish --provider="CreativeWebSolution\SvgGraphBundle\SvgGraphBundle" --tag="config"
    

    Key config options in config/svg_graph.php:

    • default_chart_type (e.g., 'line', 'bar', 'pie').
    • default_options (global styling/behavior).
  3. First Use Case: Render a Simple Graph Inject the service into a controller or Blade view:

    use CreativeWebSolution\SvgGraphBundle\Service\GraphService;
    
    public function showGraph(GraphService $graphService) {
        $data = [
            'labels' => ['Jan', 'Feb', 'Mar'],
            'values' => [10, 20, 15],
        ];
        $svg = $graphService->render('line', $data);
        return view('graphs.example', compact('svg'));
    }
    

    In Blade:

    {!! $svg !!}
    

Implementation Patterns

1. Dynamic Data Integration

  • Workflow: Fetch data from models/DB, transform into graph-compatible format.

    $users = User::selectRaw('COUNT(*) as count, MONTH(created_at) as month')
                ->groupBy('month')
                ->get()
                ->toArray();
    
    $graphData = array_map(fn($item) => [
        'labels' => ['Month ' . $item['month']],
        'values' => [$item['count']],
    ]);
    
  • Tip: Use Laravel collections to reshape data efficiently:

    $graphData = User::pluck('created_at', 'id')
                     ->mapToGroups(fn($date, $id) => ['values' => [$date]])
                     ->toArray();
    

2. Reusable Graph Components

  • Pattern: Create a dedicated GraphService facade or helper:
    // app/Helpers/GraphHelper.php
    class GraphHelper {
        public static function userActivityGraph() {
            return app(GraphService::class)->render('bar', [
                'labels' => User::select('month')->distinct()->pluck('month'),
                'values' => User::selectRaw('COUNT(*)')->groupBy('month')->pluck('COUNT(*)'),
            ]);
        }
    }
    
    Usage:
    {!! GraphHelper::userActivityGraph() !!}
    

3. API-Driven Graphs

  • Integration: Return SVG as API response (e.g., for SPAs):

    return response($graphService->render('pie', $data), 200, [
        'Content-Type' => 'image/svg+xml',
    ]);
    
  • Caching: Cache generated SVGs for performance:

    $cacheKey = 'graph:user_activity';
    $svg = Cache::remember($cacheKey, now()->addHours(1), fn() =>
        $graphService->render('line', $data)
    );
    

4. Blade Directives for Templating

  • Extend Blade with custom directives for declarative graphs:
    // app/Providers/BladeServiceProvider.php
    Blade::directive('graph', function ($type) {
        return "<?php echo app(\\CreativeWebSolution\\SvgGraphBundle\\Service\\GraphService::class)->render($type, $data); ?>";
    });
    
    Usage:
    @graph('bar', $chartData)
    

Gotchas and Tips

Pitfalls

  1. Data Format Strictness

    • The bundle expects exact key names (labels, values). Misnamed arrays will fail silently.
    • Fix: Validate input:
      $data = collect($rawData)->only(['labels', 'values'])->toArray();
      
  2. SVG Output Escaping

    • Directly outputting $svg in Blade may cause XSS warnings. Use {!! !!} or sanitize:
      $sanitizedSvg = htmlspecialchars($svg, ENT_QUOTES, 'UTF-8');
      
  3. Chart Type Limitations

    • Only supports line, bar, and pie (per README). Custom types require extension (see below).
  4. Config Overrides

    • Global default_options may conflict with per-render options. Explicitly pass overrides:
      $graphService->render('line', $data, ['colors' => ['#ff0000']]);
      

Debugging Tips

  • Inspect Generated SVG: Temporarily save to a file:
    file_put_contents(storage_path('app/debug.svg'), $svg);
    
  • Check Console Errors: Enable Laravel debug mode (APP_DEBUG=true) for missing config/dependency issues.

Extension Points

  1. Add Custom Chart Types

    • Implement CreativeWebSolution\SvgGraphBundle\Contract\ChartInterface:
      class CustomChart implements ChartInterface {
          public function render(array $data, array $options) {
              // Custom logic
              return '<svg>...</svg>';
          }
      }
      
    • Register in config/svg_graph.php:
      'charts' => [
          'custom' => \App\Charts\CustomChart::class,
      ],
      
  2. Override Default Templates

    • Publish and modify SVG templates:
      php artisan vendor:publish --tag="svg-graph-views"
      
    • Edit files in resources/views/vendor/svg_graph/.
  3. Hook into Render Pipeline

    • Use events (if the bundle supports them) or wrap the GraphService:
      $graphService = new GraphService();
      $graphService->setPreRenderCallback(function($type, $data) {
          // Modify data before rendering
          return $data;
      });
      

Performance Quirks

  • Large Datasets: SVGs bloat with >100 data points. Aggregate or paginate data.
  • Memory Usage: Complex graphs may hit PHP limits. Increase memory_limit or simplify styles.
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle