You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Laravel(PHP)无JS服务端图表生成:当前可用库及方案咨询

Great question! When it comes to server-side chart generation in Laravel without relying on JavaScript, there are solid libraries and straightforward approaches that let you render polished PNG charts directly from your backend. Let’s walk through the most reliable options and how to implement them in your Laravel project.

Core Approach

The key here is leveraging PHP-based charting libraries that use the GD extension (enabled by default in most PHP environments) to render graphics directly on the server. You can wrap this logic in a Laravel controller method, Artisan command, or service class to generate and save PNG files, or even stream them directly to the browser.

1. JpGraph

JpGraph is a battle-tested, pure-PHP charting library that supports almost every chart type you’d need—line, bar, pie, scatter, and more. It’s been around for years, has extensive documentation, and integrates smoothly with Laravel.

Setup

Install it via Composer:

composer require jpgraph/jpgraph

Basic Usage in Laravel

Create a controller method to generate and save a bar chart as PNG:

<?php

namespace App\Http\Controllers;

use JpGraph\Graph\Graph;
use JpGraph\Plot\BarPlot;

class ChartController extends Controller
{
    public function generateBarChart()
    {
        // Sample sales data
        $data = [12, 25, 18, 30, 22];
        $labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];

        // Initialize graph with dimensions
        $graph = new Graph(600, 400);
        $graph->SetScale('textlin');
        $graph->SetMargin(40, 30, 20, 40);

        // Configure titles and axis labels
        $graph->title->Set('Monthly Sales Report');
        $graph->xaxis->SetTickLabels($labels);
        $graph->yaxis->title->Set('Units Sold');

        // Create bar plot and style it
        $barPlot = new BarPlot($data);
        $barPlot->SetFillColor('#3498db');
        $barPlot->SetLegend('Total Sales');

        // Add plot to graph and position legend
        $graph->Add($barPlot);
        $graph->legend->SetPos(0.05, 0.95, 'right', 'top');

        // Save PNG to Laravel storage
        $filePath = storage_path('app/charts/sales_report.png');
        $graph->Stroke($filePath);

        return response()->json(['message' => 'Chart generated successfully', 'path' => $filePath]);
    }
}

Pros & Cons

  • Pros: Mature library, wide chart support, detailed customization options, no external dependencies beyond GD.
  • Cons: Default styling can feel a bit dated—you’ll need to tweak colors, fonts, and spacing to get a modern look.

2. PHPlot

PHPlot is a lightweight, open-source PHP charting library that focuses on simplicity. It’s great for quick, clean charts and has a lower learning curve than JpGraph.

Setup

Install via Composer:

composer require phplot/phplot

Basic Usage in Laravel

Here’s how to generate a pie chart and save it to storage:

<?php

namespace App\Http\Controllers;

use PHPlot;

class ChartController extends Controller
{
    public function generatePieChart()
    {
        // Sample device usage data
        $data = [
            ['Desktop', 45],
            ['Mobile', 35],
            ['Tablet', 20],
        ];

        // Initialize PHPlot with dimensions
        $plot = new PHPlot(500, 400);
        $plot->SetImageBorderType('plain');

        // Configure plot type and data
        $plot->SetPlotType('pie');
        $plot->SetDataType('text-data-single');
        $plot->SetDataValues($data);
        
        // Style the chart
        $plot->SetTitle('Device Usage Distribution');
        $plot->SetPieLabelType('percent');
        $plot->SetColors(['#e74c3c', '#2ecc71', '#f39c12']);

        // Save to storage
        $filePath = storage_path('app/charts/device_distribution.png');
        $plot->SetOutputFile($filePath);
        $plot->DrawGraph();

        return response()->json(['message' => 'Pie chart generated', 'path' => $filePath]);
    }
}

Pros & Cons

  • Pros: Lightweight, easy to configure, great for simple charts, minimal setup.
  • Cons: Limited advanced features compared to JpGraph; fewer chart types available (no scatter or bubble charts, for example).

3. KoolReport (For Advanced Reporting + Charts)

If you need more than just standalone charts—like full reporting with data aggregation, filters, and styled layouts—KoolReport is a great choice. It has built-in charting components that render server-side to PNG, and it integrates seamlessly with Laravel’s Eloquent ORM.

Setup

Install via Composer:

composer require koolreport/core koolreport/chart

Basic Usage

First, create a report class to define your chart:

// app/Reports/SalesTrendReport.php
<?php

namespace App\Reports;

use \koolreport\KoolReport;
use \koolreport\chart\LineChart;
use \koolreport\core\DataSource;

class SalesTrendReport extends KoolReport
{
    public function settings()
    {
        return [
            "dataSources" => [
                "sales_data" => [
                    "class" => DataSource::class,
                    "data" => [
                        ['Month', 'Sales'],
                        ['Jan', 1200],
                        ['Feb', 1800],
                        ['Mar', 1500],
                        ['Apr', 2200],
                    ]
                ]
            ]
        ];
    }

    public function createReport()
    {
        $this->src('sales_data')
            ->pipe(new LineChart())
            ->settings([
                "title" => "Quarterly Sales Trend",
                "columns" => [
                    "Month" => "category",
                    "Sales" => "value"
                ],
                "colorScheme" => "default"
            ])
            ->saveAs(storage_path('app/charts/sales_trend.png'));
    }
}

Then call the report from a controller:

public function generateTrendChart()
{
    $report = new \App\Reports\SalesTrendReport();
    $report->run();

    return response()->json(['message' => 'Trend chart generated successfully']);
}

Pros & Cons

  • Pros: Built-in data handling, advanced reporting features, modern chart styling, integrates with Laravel’s database tools.
  • Cons: Heavier than the other options; overkill if you only need simple charts.
Tips for Better Styling
  • Always tweak default colors, fonts, and padding to match your app’s design system.
  • Use high-resolution dimensions (e.g., 800x600) if you need the chart for print or high-DPI displays.
  • Cache generated charts if they don’t change frequently—store them in Laravel’s storage/app/public directory and serve them via the storage:link command to avoid regenerating on every request.

内容的提问来源于stack exchange,提问作者Yellow Kitty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:57:42