Laravel 9 Livewire Charts Tutorial Example

Laravel 9 Livewire Charts Tutorial Example

Laravel 9 livewire charts; In this tutorial, we will learn how to implement line charts, pie charts, column charts and area charts using livewire package in laravel 9 app.

So, this tutorial will guide we step by step on how to display data on line chart, area chart, bar chart , pie chart and column chart in laravel 9 app using livewire package.

Laravel 9 Livewire Charts Tutorial Example

Use the following steps to implement livewire charts using livewire package in laravel 9 apps:

  • Step 1 – Install Laravel 9 App
  • Step 2 – Connecting App to Database
  • Step 3 – Create Model & Migration using Artisan
  • Step 4 – Install Livewire Package
  • Step 5 – Install Livewire Charts Package
  • Step 5 – Build Livewire Component using Artisan
  • Step 6 – Create Route
  • Step 7 – Create View File
  • Step 8 – Run Development Server

Step 1 – Install Laravel 9 App

First of all, Execute the following command to install laravel fresh app for laravel 9 livewire charts app:

 composer create-project --prefer-dist laravel/laravel blog 

Step 2 – Connecting App to Database

In this step, Add database credentials in the .env file. So open project root directory and find .env file. Then add database detail in .env file:

DB_CONNECTION=mysql  
DB_HOST=127.0.0.1  
DB_PORT=3306  
DB_DATABASE=here database name here 
DB_USERNAME=here database username here 
DB_PASSWORD=here database password here

Step 3 – Run Migration

In this step, Execute the following command to create model name Expense.php:

php artisan make:model Expense -m 

Then open create_expenses_table.php and update the up() function, which is located inside database/migration directory:

    public function up()
    {
        Schema::create('expenses', function (Blueprint $table) {
            $table->id();
            $table->string('description');
            $table->decimal('amount');
            $table->string('type');
            $table->timestamps();
        });
    }

Now, open command prompt and execute the following command to create the table into database:

php artisan migrate

Step 4 – Install Livewire Package

In this step, Execute the following command to install the livewire package in laravel 9 app:

composer require livewire/livewire

Step 5 – Install Livewire Charts Package

In this step, execute the following command to install the livewire charts package:

composer require asantibanez/livewire-charts

Step 5: Build Livewire Component using Artisan

In this step, create the livewire components for creating a livewire charts component using the following command in laravel app. So Open cmd and execute the following command:

php artisan make:livewire LivewireCharts

This command will create the following components on the following path:

app/Http/Livewire/LivewireCharts.php
resources/views/livewire/livewire-charts.blade.php

Now, Navigate to the app/Http/Livewire folder and open the LivwireCharts.php file. Then add the following code into LivwireCharts.php file:

<?php

namespace App\Http\Livewire;

use App\Models\Expense;
use Asantibanez\LivewireCharts\Models\AreaChartModel;
use Asantibanez\LivewireCharts\Models\ColumnChartModel;
use Asantibanez\LivewireCharts\Models\LineChartModel;
use Asantibanez\LivewireCharts\Models\PieChartModel;
use Livewire\Component;

class LivewireCharts extends Component
{
    public $types = ['food', 'shopping', 'entertainment', 'travel', 'other'];

    public $colors = [
        'food' => '#f6ad55',
        'shopping' => '#fc8181',
        'entertainment' => '#90cdf4',
        'travel' => '#66DA26',
        'other' => '#cbd5e0',
    ];

    public $firstRun = true;

    protected $listeners = [
        'onPointClick' => 'handleOnPointClick',
        'onSliceClick' => 'handleOnSliceClick',
        'onColumnClick' => 'handleOnColumnClick',
    ];

    public function handleOnPointClick($point)
    {
        dd($point);
    }

    public function handleOnSliceClick($slice)
    {
        dd($slice);
    }

    public function handleOnColumnClick($column)
    {
        dd($column);
    }

    public function render()
    {
        $expenses = Expense::whereIn('type', $this->types)->get();

        $columnChartModel = $expenses->groupBy('type')
            ->reduce(function (ColumnChartModel $columnChartModel, $data) {
                $type = $data->first()->type;
                $value = $data->sum('amount');

                return $columnChartModel->addColumn($type, $value, $this->colors[$type]);
            }, (new ColumnChartModel())
                ->setTitle('Expenses by Type')
                ->setAnimated($this->firstRun)
                ->withOnColumnClickEventName('onColumnClick')
            );

        $pieChartModel = $expenses->groupBy('type')
            ->reduce(function (PieChartModel $pieChartModel, $data) {
                $type = $data->first()->type;
                $value = $data->sum('amount');

                return $pieChartModel->addSlice($type, $value, $this->colors[$type]);
            }, (new PieChartModel())
                ->setTitle('Expenses by Type')
                ->setAnimated($this->firstRun)
                ->withOnSliceClickEvent('onSliceClick')
            );

        $lineChartModel = $expenses
            ->reduce(function (LineChartModel $lineChartModel, $data) use ($expenses) {
                $index = $expenses->search($data);

                $amountSum = $expenses->take($index + 1)->sum('amount');

                if ($index == 6) {
                    $lineChartModel->addMarker(7, $amountSum);
                }

                if ($index == 11) {
                    $lineChartModel->addMarker(12, $amountSum);
                }

                return $lineChartModel->addPoint($index, $amountSum, ['id' => $data->id]);
            }, (new LineChartModel())
                ->setTitle('Expenses Evolution')
                ->setAnimated($this->firstRun)
                ->withOnPointClickEvent('onPointClick')
            );

        $areaChartModel = $expenses
            ->reduce(function (AreaChartModel $areaChartModel, $data) use ($expenses) {
                return $areaChartModel->addPoint($data->description, $data->amount, ['id' => $data->id]);
            }, (new AreaChartModel())
                ->setTitle('Expenses Peaks')
                ->setAnimated($this->firstRun)
                ->setColor('#f6ad55')
                ->withOnPointClickEvent('onAreaPointClick')
                ->setXAxisVisible(false)
                ->setYAxisVisible(true)
            );

        $this->firstRun = false;

        return view('livewire.livewire-charts')
            ->with([
                'columnChartModel' => $columnChartModel,
                'pieChartModel' => $pieChartModel,
                'lineChartModel' => $lineChartModel,
                'areaChartModel' => $areaChartModel,
            ]);
    }
}

After that, Navigate to the resources/views/livewire folder and open the livewire-charts.blade.php file. Then add the following code into livewire-charts.blade.php.blade.php file:

<div class="container mx-auto space-y-4 p-4 sm:p-0">
    <ul class="flex flex-col sm:flex-row sm:space-x-8 sm:items-center">
        <li>
            <input type="checkbox" value="travel" wire:model="types"/>
            <span>Travel</span>
        </li>
        <li>
            <input type="checkbox" value="shopping" wire:model="types"/>
            <span>Shopping</span>
        </li>
        <li>
            <input type="checkbox" value="food" wire:model="types"/>
            <span>Food</span>
        </li>
        <li>
            <input type="checkbox" value="entertainment" wire:model="types"/>
            <span>Entertainment</span>
        </li>
        <li>
            <input type="checkbox" value="other" wire:model="types"/>
            <span>Other</span>
        </li>
    </ul>

    <div class="flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4">
        <div class="shadow rounded p-4 border bg-white flex-1" style="height: 32rem;">
            <livewire:livewire-column-chart
                key="{{ $columnChartModel->reactiveKey() }}"
                :column-chart-model="$columnChartModel"
            />
        </div>

        <div class="shadow rounded p-4 border bg-white flex-1" style="height: 32rem;">
            <livewire:livewire-pie-chart
                key="{{ $pieChartModel->reactiveKey() }}"
                :pie-chart-model="$pieChartModel"
            />
        </div>
    </div>

    <div class="shadow rounded p-4 border bg-white" style="height: 32rem;">
        <livewire:livewire-line-chart
            key="{{ $lineChartModel->reactiveKey() }}"
            :line-chart-model="$lineChartModel"
        />
    </div>

    <div class="shadow rounded p-4 border bg-white" style="height: 32rem;">
        <livewire:livewire-area-chart
            key="{{ $areaChartModel->reactiveKey() }}"
            :area-chart-model="$areaChartModel"
        />
    </div>
</div>

Step 6: Create Route

In this step, Navigate to the routes folder and open web.php. Then add the following routes into web.php file:

Route::get('/livewire-charts', function () {
    return view('home');
});

Step 7: Create View File

In this step, navigate to resources/views/ folder and create one blade view files that name home.blade.php file. Then add the following code into home.blade.php file:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel 9 Livewire Charts</title>

    <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">

    <livewire:styles />
</head>
<body class="bg-gray-200 p-8">

<livewire:livewire-charts/>

<livewire:scripts />

<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

</body>
</html>
Note that, if you want to add HTML(blade views), CSS, and script code into your livewire files. So, you can use @livewireStyles, @livewireScripts, and @livewire(‘ blade views’).

Step 8: Run Development Server

Finally, we need to execute the following PHP artisan serve command to start laravel livewire charts app:

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080

Now, open browser and test laravel livewire charts app:

http://localhost:8000/livewire-charts

If we want to know more about asantibanez livewire-charts, So, we can visit this url :- https://github.com/asantibanez/livewire-charts.

Recommended Laravel Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *