
本教程演示如何在 Laravel 11 应用中利用 Larapex Charts 包创建动态 Apexcharts 图表。
Apexcharts 是一款 JavaScript 库,用于构建美观的交互式网页图表。它支持多种图表类型(例如柱状图、折线图、饼图等),方便数据可视化。用户可自定义图表外观、设置动画效果,并通过交互式操作探索数据。 Apexcharts 以其易用性和出色的数据呈现效果而广受欢迎。
我们将创建一些虚拟用户记录,并用饼图展示当年各月份的数据。 以下步骤将指导您在 Laravel 11 应用中添加图表。
步骤 1:安装 Laravel 11
此步骤非必需。如果您尚未创建 Laravel 应用,请执行以下命令:
composer create-project laravel/laravel example-app
步骤 2:安装 arielmejiadev/larapex-charts
使用 Composer 安装 arielmejiadev/larapex-charts 包:
composer require arielmejiadev/larapex-charts
然后发布配置文件:
php artisan vendor:publish --tag=larapex-charts-config
步骤 3:创建路由
创建一个简单的路由,用于生成简单的折线图。在 routes/web.php 文件中添加以下路由:
<?php
use IlluminateSupportFacadesRoute;
use AppHttpControllersApexchartsController;
Route::get('charts', [ApexchartsController::class, 'index']);
?>步骤 4:创建图表类
在 app 文件夹下创建 Charts 文件夹。然后,创建 MonthlyUsersChart.php 文件,并添加以下代码:
<?php
namespace AppCharts;
use ArielMejiaDevLarapexChartsLarapexChart;
use AppModelsUser;
use DB;
class MonthlyUsersChart
{
protected $chart;
public function __construct(LarapexChart $chart)
{
$this->chart = $chart;
}
public function build()
{
$users = User::select(DB::raw("count(*) as count"), DB::raw("MONTHNAME(created_at) as month_name"))
->whereYear('created_at', date('Y'))
->groupBy(DB::raw("MONTH(created_at)"))
->pluck('count', 'month_name');
return $this->chart->pieChart()
->set

