ApexCharts is a JavaScript library used for creating interactive and visually appealing charts on websites. It supports various chart types like bar, line, and pie, and provides options to customize their appearance, add animations, and enable interactivity. With its user-friendly design, ApexCharts makes data visualization straightforward and aesthetically pleasing.
Table Of Content
1 Prerequisites
1.) PHP version of >= 8.2
2.) Composer
3.) Mysql
2 Introduction
In this guide, we'll demonstrate how to integrate ApexChart with filter options in Laravel 11. You'll learn to create dummy user records and display a dynamic line chart featuring the months of the current year. Follow these steps to add powerful chart functionality to your Laravel 11 application.
Edit the migration file to define the table structure, then run:
<?php
se Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};
Run the migration:
php artisan migrate
5 Create Model
Define the User model in app/Models/User.php. Use this model to work with the users table.
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var list
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
6 Create Factory Class
Create a factory class:
php artisan make:factory UserFactory
Update the factory to generate sample data and seed the database:
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Support\Carbon;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
'created_at' => Carbon::createFromTimestamp(fake()->unixTime()),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
To generate 100 dummy records, use:
php artisan tinker
User::factory()->count(100)->create()
7 Create Controller (UserController)
Create a UserController for chart data handling:
php artisan make:controller UserController
In the controller, implement index and filterData methods to populate the charts dynamically. This allows you to explore how to create dynamic charts with filter options in ApexCharts using Laravel 11.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index(Request $request)
{
$charts_data = User::selectRaw('count(id) AS data,MONTH(created_at) AS month')->whereYear('created_at',"2024")->groupBy('month')->get();
$chart_data=array();
foreach($charts_data as $chart)
{
$temp=array();
$temp['x']='2024-'.$chart['month'];
$temp['y']=$chart['data'];
$chart_data[]=$temp;
}
$charts=$chart_data;
return view('index', compact('charts'));
}
function filterData(Request $request)
{
$year=$request->input('year');
$charts=User::selectRaw('count(id) AS data,MONTH(created_at) AS month')->whereYear('created_at',$year)->groupBy('month')->get();
$chart_data=array();
foreach($charts as $chart)
{
$temp=array();
$temp['x']=$year.'-'.$chart['month'];
$temp['y']=$chart['data'];
$chart_data[]=$temp;
}
$data['charts']=$chart_data;
return $data;
}
}
?>
8 Create view (Blade)
Create resources/views/index.blade.php to render the chart. Use ApexCharts for visualizing user data interactively.
Add routes in routes/web.php for loading and filtering chart data.
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::get('/', function () {
return view('welcome');
});
Route::get('users',[UserController::class,'index'])->name('users.index');
Route::post('search',[UserController::class,'filterData'])->name('users.search');
10 Folder Structure
11 Run Laravel Server to Test the App
Start the Laravel server:
php artisan serve
Visit the app to view dynamic charts with filter options integrated seamlessly.
12 Conclusion
You've now learned how to integrate ApexChart with filter options in Laravel 11 and create dynamic charts using this powerful JavaScript library. Implementing these features allows your application to offer enhanced data visualization capabilities.