Laravel 12 Chart Generate Using Apexchart
Laravel 12 is a popular framework and widely used for making chart data, nice dashboard, realtime data updates for different dashboards. Laravel framework can easily handle chart creation such as bar chart, line chart, pie chart or scatter. We just have to follow some steps and guidelines for using that in project. In this article we will use popular open source Apexjs chart library for creating chart. We will follow some steps to complete
Steps to Create Chart using Apexchart in Laravel 12
- Installation of Laravel 12 Framework
- Install Apexchart
- Create Controller
- Create Necessary Route
- Create Blade File
- Create and Modify Js file
- Run and Preview Project
Installation of Laravel 12 Framework
Here we will create a fresh laravel 12 project for showing chart in browser frontend. We can also use our existing laravel projects as well. But the processes or steps are fully same.
composer create-project --prefer-dist laravel/laravel laravel12-chart 12.* cd laravel12-chart
Install Apexchart
npm install apexcharts --save
Create Controller
namespace App\Http\Controllers; use App\Models\Sale; use Illuminate\Http\Request; class ChartController extends Controller { public function index(Request $request) { $sales = Sale::all(); $months = $sales->pluck('month'); $amounts = $sales->pluck('amount'); return view('chart', compact('months', 'amounts')); } }
Create Necessary Route
use App\Http\Controllers\ChartController; use Illuminate\Support\Facades\Route; Route::get('chart', [ChartController::class, 'index']); require __DIR__ . '/auth.php';
Create Blade File
<!DOCTYPE html> <html> <head> <title>ApexChart in Laravel 12</title> @vite('resources/css/app.css') </head> <body> <div id="wrapper" class="container"> <h2>Laravel 12 Apex Chart Demo</h2> <div id="chart" data-months='@json($months)' data-amounts='@json($amounts)'> </div> </div> @vite('resources/js/app.js') </body> </html>
Create and Modify Js Files
//resources/js/chart.js import ApexCharts from 'apexcharts'; function renderSalesChart(months, amounts) { const options = { chart: { type: 'bar', height: 350 }, series: [{ name: 'Sales', data: amounts }], xaxis: { categories: months } }; const chart = new ApexCharts(document.querySelector("#chart"), options); chart.render(); } export default renderSalesChart;
//resources/js/app.js import './bootstrap'; import renderSalesChart from './chart'; // Use these if you are embedding dynamic data in the blade file const months = JSON.parse(document.getElementById('chart').dataset.months); const amounts = JSON.parse(document.getElementById('chart').dataset.amounts); renderSalesChart(months, amounts);
Run and Preview Project
