Home >Backend Development >PHP Tutorial >How To Create Dynamic Apexcharts Using Larapex Charts Package in Laravel 11
This tutorial demonstrates building dynamic ApexCharts within a Laravel 11 application using the larapex-charts package.
ApexCharts, a JavaScript charting library, simplifies the creation of visually appealing and interactive charts for websites. Its versatility allows for various chart types (bar, line, pie, etc.), customization options, animations, and interactive data exploration. Its ease of use and attractive output contribute to its popularity.
This example generates sample user data and displays a pie chart representing each month of the current year. Let's integrate this chart into your Laravel 11 project.
Creating Dynamic Apexcharts with Larapex Charts in Laravel 11
Step 1: Setting up Laravel 11 (Optional)
This step is only necessary if you haven't already created a Laravel 11 application. Use the following command:
<code class="language-bash">composer create-project laravel/laravel example-app</code>
Step 2: Installing the larapex-charts Package
Install the arielmejiadev/larapex-charts
package via Composer:
<code class="language-bash">composer require arielmejiadev/larapex-charts</code>
Publish the configuration file:
<code class="language-bash">php artisan vendor:publish --tag=larapex-charts-config</code>
Step 3: Defining the Route
Create a route to handle the chart generation. Add this to your routes/web.php
file:
<code class="language-php"><?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\ApexchartsController; Route::get('charts', [ApexchartsController::class, 'index']);</code>
Step 4: Creating the Chart Class
Create a Charts
directory within your app
directory. Inside, create MonthlyUsersChart.php
with the following code:
<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>
The above is the detailed content of How To Create Dynamic Apexcharts Using Larapex Charts Package in Laravel 11. For more information, please follow other related articles on the PHP Chinese website!