
本教程演示如何在 Laravel 11 应用中利用 Larapex Charts 包创建动态 Apexcharts 图表。
Apexcharts 是一款 JavaScript 库,用于构建美观的交互式网页图表。它支持多种图表类型(例如柱状图、折线图、饼图等),方便数据可视化。用户可自定义图表外观、设置动画效果,并通过交互式操作探索数据。 Apexcharts 以其易用性和出色的数据呈现效果而广受欢迎。
我们将创建一些虚拟用户记录,并用饼图展示当年各月份的数据。 以下步骤将指导您在 Laravel 11 应用中添加图表。
步骤 1:安装 Laravel 11
此步骤非必需。如果您尚未创建 Laravel 应用,请执行以下命令:
<code class="bash">composer create-project laravel/laravel example-app</code>
步骤 2:安装 arielmejiadev/larapex-charts
使用 Composer 安装 arielmejiadev/larapex-charts 包:
<code class="bash">composer require arielmejiadev/larapex-charts</code>
然后发布配置文件:
<code class="bash">php artisan vendor:publish --tag=larapex-charts-config</code>
步骤 3:创建路由
创建一个简单的路由,用于生成简单的折线图。在 routes/web.php 文件中添加以下路由:
<code class="php"><?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ApexchartsController;
Route::get('charts', [ApexchartsController::class, 'index']);
?></code>步骤 4:创建图表类
在 app 文件夹下创建 Charts 文件夹。然后,创建 MonthlyUsersChart.php 文件,并添加以下代码:
<code class="php">
<?php
namespace App\Charts;
use ArielMejiaDev\LarapexCharts\LarapexChart;
use App\Models\User;
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</code>以上就是如何在 Laravel 11 中使用 Larapex Charts 包创建动态 Apexcharts的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号