Livewire Charts in Laravel 10

Livewire Charts in Laravel 10

If you want to create Line Chart, Pie Chart, Column Chart and Area Chart in Laravel Web Application using Livewire Chart. And also want to render charts from dynamic database in these charts. Then this tutorial is for you. So, in this tutorial guide, you will learn to create line charts, pie charts, column charts, and area charts in Laravel 10 app using Livewire package.

Livewire Charts in Laravel 10

By following this tutorial guide, you’ll learn how to create these types of charts in a Laravel 10 app using the Livewire package.

  • Step 1 – Setup New Laravel 10 Project
  • Step 2 – Configure Database to Laravel Project
  • Step 3 – Create Model & Migration using Artisan
  • Step 4 – Install Livewire Package
  • Step 5 – Install Livewire Charts Package
  • Step 5 – Create Livewire Component using Artisan
  • Step 6 – Add Routes
  • Step 7 – Create View File
  • Step 8 – Run Development Server

Step 1 – Setup New Laravel 10 Project

Firstly , Open your terminal or cmd(command prompt).

Then execute the following command into it to install laravel fresh project in your server:

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

Step 2 – Configure Database to Laravel Project

Once you have installed laravel app in your server. Then you need to configure the database with laravel apps.

So, open your 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 your 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 your database:

php artisan migrate

Step 4 – Install Livewire Package

In this step, Execute the following command to install livewire package in Laravel 10 app:

composer require livewire/livewire

Step 5 – Install Livewire Charts Package

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

composer require asantibanez/livewire-charts

Step 5 – Create Livewire Component using Artisan

In this step, create the livewire components for creating a livewire charts component using the following command in Laravel 10 app. So Open your 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 app/Http/Livewire folder and open LivwireCharts.php file. Then add the following code into your 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 resources/views/livewire folder and open livewire-charts.blade.php file. Then add the following code into your 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: Add Routes

In this step, Navigate to routes folder and open web.php. Then add the following routes into your 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 your 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 10 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, you need to execute the following PHP artisan serve command to start your 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 10 livewire charts app:

http://localhost:8000/livewire-charts

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

Recommended Laravel Posts

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 *