I'll show you how to use the console TV charts in Laravel 9 today. It may be necessary to work with a js library to add attractive visuals if you need to add some graphs to your views, however even with a good library like ChartJS, implementing this is not that simple.

Step 1: Download Laravel

Installing a fresh Laravel application will kick off the tutorial. If the project has already been created, skip the next step.

composer create-project laravel/laravel example-app

Step 2 : Installing ConsoleTvs Package

Now Install the consoletvs/charts:6 package using the command line in the laravel 9 app in this step.

composer require consoletvs/charts:6

That is all you need to do to install the package if you are using Laravel 9 or higher, thanks to the autodiscover feature.

Add the following line to the providers section of the config/app.php file if you are using Laravel versions lower than 9.

ConsoleTVs\Charts\ChartsServiceProvider::class,

Also, use the following command to publish the settings in the terminal:

php artisan vendor:publish --tag=charts_config

The installation of the package is now complete!

Step 3: Use the Package

In this phase, we'll develop a chart class using the Artisan cli.

php artisan make:chart UserChart

Now, we can see a folder called charts in the app directory, and inside of that folder is our new class UserChart.php.

Step 4: Add Controller

I'll give a simple example, but you may add as much complexity as you like. We'll develop a resource-type controller to display a user chart.

php artisan make:controller UserChartController

You may now edit the code in app/Http/Controllers/UserChartController.php by holding only the index method and deleting the remaining entire methods. The result will look like this:

app/Http/Controllers/UserChartController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

}

I'll generate some fictitious data to make things simpler, but you may use Eloquent's queryBuilder to create queries as needed. I'll import the previously built new chart class into the controller and begin creating a chart with the Laravel 9 chart api fluid syntax:

app/Http/Controllers/UserChartController.php

<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $usersChart = new UserChart;
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'line', [10, 25, 13]);
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}

Step 5: Add Blade File

We now need a view to display the data; in the previous code sample, the index method returns a view for users charts. Accordingly, I will create a file called users.blade.php in the resources/views/ directory with the following contents:

resources/views/users.blade.php

@extends('layouts.app')

@section('content')
<h1>Sales Graphs</h1>

<div style="width: 50%">
    {!! $salesChart->container() !!}
</div>
@endsection

Now that the chart script has been passed to the view file, all that is left to do is to add the chart's CSS and JS libraries. To keep things simple, we'll use the layout app blade file, which can be found in resources/views/layout/app.blade.php. Here, we'll add the following line to the header section at the bottom:

resources/views/layout/app.blade.php

<head>
    <meta charset="utf-8">
    ...
    {{-- ChartScript --}}
    @if($usersChart)
    {!! $usersChart->script() !!}
    @endif
</head>

Before the html closing element in the file app.blade.php, we will add the scripts to add the JS library file:

@extends('layouts.app')

@section('content')
<h1>Users Graphs</h1>

<div style="width: 50%">
    {!! $usersChart->container() !!}
</div>
@endsection

Step 6: Add Route

Finally, we simply require a route to access the graphic view. You can add a route using the get function to access the users in the routes/web.php file. In the following example, I set a route to "sales" in the ChartController class' method index():

routes/web.php

<?php

use App\Http\Controllers\UserChartController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('users', 'UserChartController@index');

app/Http/Controllers/UserChartController.php

<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $usersChart = new UserChart;
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'line', [10, 25, 13])
            ->color("rgb(255, 99, 132)")
            ->backgroundcolor("rgb(255, 99, 132)");
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}

In the case of "line" or "area" charts, the method "colour" sets the border colour. As a param, it takes a string containing the rgb or rgba colour.

The "backgroundcolor" method sets the area colour, the fill colour, and the param parameter, which calls for a string of rgb or rgba colour.

The "fill" method needs a boolean value, and if it is set to false, a chart is filled by default.

The "linetension" method reduces curvature and calls for a float between 0.0 and 1.0.

The "dashed" technique uses a dashed line and calls for an array.

Customize the chart

The following techniques can be used to modify the chart:

  • The "minimalist" method eliminates the chart legend and the grid background. It also requires a boolean.
  • To conceal the legend, set the "displaylegend" method's optional parameter to false. The method's required boolean value is true by default.
  • To paint the chart's backdrop grid, the "displayaxes" method needs a boolean parameter, which by default is true. To make it invisible, set the parameter to false.
  • In area and line charts, the technique "barWidth" does nothing because it needs a double.

app/Http/Controllers/UserChartController.php

<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $usersChart = new UserChart;
        $usersChart->title('Users by Months', 30, "rgb(255, 99, 132)", true, 'Helvetica Neue');
        $usersChart->barwidth(0.0);
        $usersChart->displaylegend(false);
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'line', [10, 25, 13])
            ->color("rgb(255, 99, 132)")
            ->backgroundcolor("rgb(255, 99, 132)")
            ->fill(false)
            ->linetension(0.1)
            ->dashed([5]);
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}

Doughnut Example

app/Http/Controllers/UserChartController.php

<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $borderColors = [
            "rgba(255, 99, 132, 1.0)",
            "rgba(22,160,133, 1.0)",
            "rgba(255, 205, 86, 1.0)",
            "rgba(51,105,232, 1.0)",
            "rgba(244,67,54, 1.0)",
            "rgba(34,198,246, 1.0)",
            "rgba(153, 102, 255, 1.0)",
            "rgba(255, 159, 64, 1.0)",
            "rgba(233,30,99, 1.0)",
            "rgba(205,220,57, 1.0)"
        ];
        $fillColors = [
            "rgba(255, 99, 132, 0.2)",
            "rgba(22,160,133, 0.2)",
            "rgba(255, 205, 86, 0.2)",
            "rgba(51,105,232, 0.2)",
            "rgba(244,67,54, 0.2)",
            "rgba(34,198,246, 0.2)",
            "rgba(153, 102, 255, 0.2)",
            "rgba(255, 159, 64, 0.2)",
            "rgba(233,30,99, 0.2)",
            "rgba(205,220,57, 0.2)"

        ];
        $usersChart = new UserChart;
        $usersChart->minimalist(true);
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'doughnut', [10, 25, 13])
            ->color($borderColors)
            ->backgroundcolor($fillColors);
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}

Bar example

With a little work and the Laravel installation's default bootstrap:

app/Http/Controllers/UserChartController.php

<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $borderColors = [
            "rgba(255, 99, 132, 1.0)",
            "rgba(22,160,133, 1.0)",
            "rgba(255, 205, 86, 1.0)",
            "rgba(51,105,232, 1.0)",
            "rgba(244,67,54, 1.0)",
            "rgba(34,198,246, 1.0)",
            "rgba(153, 102, 255, 1.0)",
            "rgba(255, 159, 64, 1.0)",
            "rgba(233,30,99, 1.0)",
            "rgba(205,220,57, 1.0)"
        ];
        $fillColors = [
            "rgba(255, 99, 132, 0.2)",
            "rgba(22,160,133, 0.2)",
            "rgba(255, 205, 86, 0.2)",
            "rgba(51,105,232, 0.2)",
            "rgba(244,67,54, 0.2)",
            "rgba(34,198,246, 0.2)",
            "rgba(153, 102, 255, 0.2)",
            "rgba(255, 159, 64, 0.2)",
            "rgba(233,30,99, 0.2)",
            "rgba(205,220,57, 0.2)"

        ];
        $usersChart = new UserChart;
        $usersChart->minimalist(true);
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'bar', [10, 25, 13])
            ->color($borderColors)
            ->backgroundcolor($fillColors);
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}

blade view with some decoration bootstrap

@extends('layouts.app')

@section('content')
<div class="container">
    <h1>Users Graphs</h1>
    <div class="row">
        <div class="col-6">
            <div class="card rounded">
                <div class="card-body py-3 px-3">
                    {!! $usersChart->container() !!}
                </div>
            </div>
        </div>
    </div>
</div>
@endsection


Recommended Posts

View All

Laravel 9 Form Validation Example


In this Laravel 9 validation tutorial, I'll demonstrate how to validate form input and provide an error message before saving it to the database.

How To Use WYSIHTML5 Editor In Laravel 9?


wysihtml5 editor example, laravel wysihtml5 editor example, wysihtml5 laravel, wysihtml5 editor example in laravel, wysihtml5 with laravel, wysihtml5...

Laravel Many to Many Polymorphic Relationship


Laravel many to many polymorphic relations, many to many polymorphic relations Laravel, polymorphic relations eloquent Laravel, Laravel morphToMany ex...

Laravel 9 Create Multi Language Website Example Tutorial


Learn how to create a multi-language website with Laravel 9 through our example tutorial. Develop your skills and broaden your audience reach today!

Google Map with Multiple Marker and Info Box in Laravel


This tutorial will teach you how to use Laravel to integrate a Google Map with numerous markers and an info box.