本教程演示使用 larapex-charts 包在 Laravel 11 应用程序中构建动态 ApexCharts。
ApexCharts 是一个 JavaScript 图表库,可简化为网站创建具有视觉吸引力和交互式图表的过程。 其多功能性允许使用各种图表类型(条形图、折线图、饼图等)、自定义选项、动画和交互式数据探索。 它的易用性和有吸引力的输出使其广受欢迎。
此示例生成示例用户数据并显示代表当年每个月的饼图。让我们将此图表集成到您的 Laravel 11 项目中。
在 Laravel 11 中使用 Larapex 图表创建动态 Apexchart
第 1 步:设置 Laravel 11(可选)
仅当您尚未创建 Laravel 11 应用程序时才需要执行此步骤。 使用以下命令:
<code class="language-bash">composer create-project laravel/laravel example-app</code>
第 2 步:安装 larapex-charts 软件包
通过 Composer 安装 arielmejiadev/larapex-charts
包:
<code class="language-bash">composer require arielmejiadev/larapex-charts</code>
发布配置文件:
<code class="language-bash">php artisan vendor:publish --tag=larapex-charts-config</code>
第 3 步:定义路线
创建一条路线来处理图表生成。 将其添加到您的 routes/web.php
文件中:
<code class="language-php"><?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\ApexchartsController; Route::get('charts', [ApexchartsController::class, 'index']);</code>
第 4 步:创建图表类
在您的 Charts
目录中创建一个 app
目录。在里面,使用以下代码创建 MonthlyUsersChart.php
:
<code class="language-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中文网其他相关文章!