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

Jpgraph Laravel Package

mitoteam/jpgraph

Composer wrapper for JpGraph 4.4.3 with PHP 5.5–8.5 support. Install via composer and call MtJpGraph::load() to autoload the JpGraph core and modules (bar, line, etc.), with optional Extended Mode, then use standard JpGraph classes like Graph.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package Add to your Laravel project via Composer:

    composer require mitoteam/jpgraph
    
  2. Load the Library Load required modules (e.g., bar, line) in your controller, service, or blade template:

    use mitoteam\jpgraph\MtJpGraph;
    
    MtJpGraph::load(['bar', 'line']); // Load specific modules
    
  3. Generate a Basic Chart Use the original JpGraph classes to create a chart:

    $graph = new Graph(600, 400);
    $graph->SetMargin(40, 30, 20, 40);
    $graph->SetShadow();
    $graph->SetColor('beige');
    
    // Add data
    $data = array(10, 20, 15, 30, 25);
    $bplot = new BarPlot($data);
    $graph->Add($bplot);
    
    // Output to browser or save to file
    $graph->Stroke();
    
  4. Output the Chart

    • Browser Output: Call $graph->Stroke() directly in a controller or Blade template.
    • File Output: Save to a file or storage:
      $graph->Stroke('my_chart.png');
      
    • Base64 for APIs: Encode the image for API responses:
      $img = $graph->Stroke(_JPGGRAPH_BROWSER);
      $base64 = base64_encode($img);
      return response($base64, 200, ['Content-Type' => 'image/png']);
      

First Use Case: Dynamic Laravel Report

Scenario: Generate a monthly sales report with a bar chart in a Laravel admin panel.

  1. Create a Controller Method:

    public function generateSalesReport()
    {
        MtJpGraph::load(['bar']);
        $graph = new Graph(800, 500);
        $graph->SetMargin(50, 30, 40, 50);
    
        // Fetch sales data from database
        $salesData = Sales::whereYear('created_at', now()->year)
            ->whereMonth('created_at', now()->month)
            ->pluck('amount')
            ->toArray();
    
        $bplot = new BarPlot($salesData);
        $graph->Add($bplot);
    
        // Customize chart
        $graph->title->Set('Monthly Sales Report');
        $graph->xaxis->SetTickLabels(['Jan', 'Feb', 'Mar', 'Apr', 'May']);
    
        // Output to browser or save to storage
        return response($graph->Stroke(_JPGGRAPH_BROWSER), 200, ['Content-Type' => 'image/png']);
    }
    
  2. Route the Endpoint:

    Route::get('/reports/sales-chart', [ReportController::class, 'generateSalesReport']);
    
  3. Display in Blade:

    <img src="{{ route('reports.sales-chart') }}" alt="Sales Report">
    

Where to Look First

  • Original JpGraph Documentation for chart types, methods, and customization options.
  • Examples Gallery for ready-to-use code snippets.
  • Package README for PHP version compatibility notes and Extended Mode usage.
  • Laravel Storage Integration: Use storage_path() to save charts dynamically:
    $path = storage_path('app/charts/sales_' . now()->format('Y-m') . '.png');
    $graph->Stroke($path);
    

Implementation Patterns


Core Workflows

1. Dynamic Chart Generation in Controllers

Use JpGraph to generate charts on-demand for API responses, emails, or PDFs.

Example: API Response with Chart

public function getUserActivityChart(Request $request)
{
    MtJpGraph::load(['line']);
    $graph = new Graph(600, 300);

    // Fetch user activity data
    $activity = UserActivity::where('user_id', $request->user_id)
        ->orderBy('created_at')
        ->pluck('value')
        ->toArray();

    $lineplot = new LinePlot($activity);
    $graph->Add($lineplot);

    // Customize
    $graph->title->Set('User Activity');
    $graph->xaxis->SetLabelAngle(45);

    // Return as base64
    $img = $graph->Stroke(_JPGGRAPH_BROWSER);
    return response($img, 200, ['Content-Type' => 'image/png']);
}

2. Batch Processing with Queues

Generate charts asynchronously for large datasets (e.g., monthly reports for all customers).

Example: Queued Chart Generation

// Job class
public function handle()
{
    MtJpGraph::load(['pie']);
    $graph = new Graph(500, 400);

    // Fetch data for customer
    $data = Customer::find($this->customerId)->transactions->pluck('amount')->toArray();
    $p1 = new PiePlot($data);

    $graph->Add($p1);
    $graph->Stroke(storage_path("app/reports/customer_{$this->customerId}.png"));
}

// Dispatch job
GenerateCustomerReportJob::dispatch($customerId);

3. Laravel Blade Integration

Embed charts directly in Blade templates for admin panels or user dashboards.

Example: Dynamic Blade Chart

@php
    MtJpGraph::load(['bar']);
    $graph = new Graph(600, 300);
    $data = [100, 200, 150, 300, 250];
    $bplot = new BarPlot($data);
    $graph->Add($bplot);
    $graph->title->Set('Monthly Performance');
@endphp

<img src="data:image/png;base64,{{ base64_encode($graph->Stroke(_JPGGRAPH_BROWSER)) }}">

4. PDF/Email Reports with DomPDF

Combine JpGraph charts with text content in PDFs or emails.

Example: PDF Report with Chart

use Dompdf\Dompdf;

public function generatePdfReport()
{
    MtJpGraph::load(['line']);
    $graph = new Graph(500, 300);
    $data = [10, 20, 15, 30, 25];
    $lineplot = new LinePlot($data);
    $graph->Add($lineplot);

    // Save chart temporarily
    $chartPath = tempnam(sys_get_temp_dir(), 'jpgraph_');
    $graph->Stroke($chartPath);

    // Create HTML with chart
    $html = '<h1>Report</h1><img src="'.$chartPath.'">';

    // Generate PDF
    $dompdf = new Dompdf();
    $dompdf->loadHtml($html);
    $dompdf->render();
    return $dompdf->stream('report.pdf');
}

Integration Tips

1. Laravel Service Providers

Centralize JpGraph loading in a service provider to avoid repetitive MtJpGraph::load() calls.

Example: JpGraphServiceProvider

public function register()
{
    $this->app->singleton('jpgraph', function () {
        return new class {
            public function __invoke($modules = ['bar', 'line']) {
                MtJpGraph::load($modules);
            }
        };
    });
}

Usage in Controllers:

public function __construct(private JpGraph $jpgraph) {}

public function showChart()
{
    $this->jpgraph(['pie']);
    // Use JpGraph classes...
}

2. Caching Charts

Cache generated charts to improve performance for frequently accessed reports.

Example: Cached Chart Response

public function getCachedChart()
{
    $cacheKey = 'chart_sales_monthly_' . now()->format('Y-m');
    $chart = Cache::remember($cacheKey, now()->addHours(1), function () {
        MtJpGraph::load(['bar']);
        $graph = new Graph(600, 300);
        // ... generate chart ...
        return $graph->Stroke(_JPGGRAPH_BROWSER);
    });

    return response($chart, 200, ['Content-Type' => 'image/png']);
}

3. Custom Themes

Define reusable chart themes using Laravel config or environment variables.

Example: Config-Based Theming

// config/jpgraph.php
return [
    'theme' => [
        'background' => 'white',
        'font' => 'arial.ttf',
        'colors' => ['#4CAF50', '#2196F3', '#FF9800'],
    ],
];

Apply Theme in Code:

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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata