PHP code example of radiatecode / dachartjs

1. Go to this page and download the library: Download radiatecode/dachartjs library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

radiatecode / dachartjs example snippets


namespace App\Charts;

use RadiateCode\DaChartjs\Abstracts\AbstractChart;
use RadiateCode\DaChartjs\Facades\Dataset;
use RadiateCode\DaChartjs\Types\Bar\VerticalBarChart;

class MonthlyChart extends AbstractChart
{
    protected function chartTitle(): string
    {
        return 'Month Chart';
    }

    protected function chartType(): string
    {
        return VerticalBarChart::class;
    }

    protected function labels(): array
    {
        return ['January','February','March'];
    }

    protected function datasets(): array
    {
        return [
            Dataset::general('Project',[20, 30,55])->make(),
            Dataset::general('Task',[50, 80,44])->make(),
            Dataset::general('Task',[70, 75,99])->make()
        ];
    }
}

use App\Charts\MonthlyChart;

class ReportController extends Controller 
{  
    public function monthlyChart()
    {
        $monthlyChart = new MonthlyChart();
        
        return view('reports.monthly')->with('monthlyChart',$monthlyChart->template());
    }
}

namespace App\Charts;

use RadiateCode\DaChartjs\Abstracts\AbstractChart;
use RadiateCode\DaChartjs\Types\Bar\VerticalBarChart;

class SalesChart extends AbstractChart
{
    protected function chartTitle(): string
    {
        return 'Monthly Sales Chart';
    }

    protected function chartType(): string
    {
        return VerticalBarChart::class;
    }

    protected function labels(): array
    {
        return []; // empty labels, will be loaded by ajax
    }

    protected function datasets(): array
    {
        return []; // empty datasets, will be loaded by ajax
    }
}

use App\Charts\SalesChart;

class ReportController extends Controller 
{
    public function salesChart(){
        $monthlySalesChart = new SalesChart();
        
        return view('reports.top_sales')->with('monthlySalesChart',$monthlySalesChart->template());
    }
}

Route::get('fetch/monthly/top/sales/chart','ReportController@monthlyTopSales');

use RadiateCode\DaChartjs\Facades\Dataset;
use RadiateCode\DaChartjs\Facades\ChartResponse;
use RadiateCode\DaChartjs\Enums\ChartColor;
use App\Models\Order;

class ReportController extends Controller 
{
    public function monthlyTopSales(Request $request)
    {
        $sales = Order::where('month',$request->get('month_name'))
                        ->orderBy('sold_qty','desc')
                        ->groupBy('product_id')
                        ->selectRaw('product_name, SUM(qty) as sold_qty')
                        ->take(4)->get();
                        
         $soldProducts = $sales->pluck('product_name')->toArray();
         $soldQty = $sales->pluck('sold_qty')->toArray();
    
         $datasets = [
            Dataset::label('Top Sales')
                ->data($soldQty)
                ->backgroundColor([
                    ChartColor::LIGHT_SLATE_BLUE,
                    ChartColor::BRIGHT_TURQUOISE,
                    ChartColor::ELECTRIC_PURPLE,
                    ChartColor::EGGPLANT
                ])->make(),
        ];
        
        return ChartResponse::labels($soldProducts)->datasets($datasets)->toJson();
    }
}

'providers' => [
    ...,
    RadiateCode\DaChartjs\ChartServiceProvider::class,
]

namespace App\Charts;

use RadiateCode\DaChartjs\Abstracts\AbstractChart;
use RadiateCode\DaChartjs\Facades\Dataset;
use RadiateCode\DaChartjs\Types\Bar\HorizontalBarChart;

class MonthlyCompletionChart extends AbstractChart
{
	/**
     * Chart title
     *
     * ---------------------------------------------------------------------
     * Note: it can be use as chart id or chart name in js & html
     * ---------------------------------------------------------------------
     * @return string
     */
    protected function chartTitle(): string
    {
        return 'Month Chart';
    }

	/**
     * Chart type
     *
     * ---------------------------------------------------------------------
     * Note: Chart type must be path of a concrete class of TypeInterface
     * [ex: HorizontalBarChart::class]
     * ---------------------------------------------------------------------
     * @return string
     */
    protected function chartType(): string
    {
        return HorizontalBarChart::class;
    }

    /**
     * Chart labels
     *
     * -----------------------------------------------------------------------
     * Note: This labels are used to label the data index (default x axis)
     * -----------------------------------------------------------------------
     * @return array
     */
    protected function labels(): array
    {
        return ['January','February','March'];
    }

     /**
     * Dataset
     *
     * --------------------------------------------------------------
     * Note: datasets can be generate by Dataset Facade 
     * Or, we can pass custom array with dataset properties,
     * --------------------------------------------------------------
     * @return array
     */
    protected function datasets(): array
    {
        return [
            Dataset::general('Project',[20, 30,55])->make(),
            Dataset::general('Task',[50, 80,44])->make(),
            Dataset::general('Task',[70, 75,99])->make()
        ];
    }
}

> class MonthlyCompletionChart extends AbstractChart
> {
>     /**
>     * Change default options when necessary
>     *
>     * @override method
>     * @return array
>     */  
>     protected function changeDefaultOptions(): array
>     {
>         return [
>              // dot used in key is to indicate nested array level of option properties
>             'plugins.title.text' => 'Monthly Completion Chart',
>             'plugins.title.color' => 'red',
>         ];
>     }
> }
> 

> class MonthlyCompletionChart extends AbstractChart
> {
>     /**
>     * Use custom options if we don't want to use defaults
>     *
>     * @override method
>     * @return array|string
>     */  
>     protected function options()
>     {
>          return [
>                 'responsive' => true,
>                 'scales' => [
>                     'xAxes' => [
>                         'ticks' => [
>                             'beginAtZero' => true,
>                             'maxRotation' => 90,
>                             'minRotation' => 90
>                         ]
>                     ]
>                 ],
>                 'plugins'    => [
>                     'title'  => [
>                         'text'     => 'My Chart Title',
>                         'position' => 'top',
>                         'display'  => true,
>                         'color'    => 'yellow',
>                     ],
>                 ]
>             ];
>            
>            /** 
>            * Json string can be use
>            */
>            // return "{
>            //   responsive : true,
>            //   plugins    : {
>            //       title  : {
>            //           text     : 'My Chart Title',
>            //           position : 'top',
>            //           display  : true,
>            //           color    : 'yellow',
>            //       },
>            //  },
>            // }"
>     }
> }
> 

>  protected function chartSize(): array
>    {
>        return [
>            'height' => 230
>            // 'width' => 400 // width is optional for responsive chart
>        ];
>    }
> 

use App\Charts\MonthlyCompletionChart;

class ReportController extends Controller
{
    public function monthlyChart(){
        $myChart =  new MonthlyCompletionChart();
        
        return view('reports.monthly')->with('myChart',$myChart->template());
    }
}

use RadiateCode\DaChartjs\Chart;
use RadiateCode\DaChartjs\Types\Bar\HorizontalBarChart;
...................

$barChart = (new Chart('Monthly Chart', HorizontalBarChart::class))
        ->labels(['January', 'February','March']) //labeling the data index of the chart
        ->datasets([ // Datasets build by Dataset facade
            Dataset::label('Task')->data([20, 30,55])->backgroundColor('yellow')
            ->borderColor('black')->make(),
            Dataset::label('Project')->data([50, 80,44])->backgroundColor('green')
                ->borderColor('white')->make(),
            Dataset::label('Issue')->data([70, 75,99])->backgroundColor('red')
                ->borderColor('white')->make(),
        ])
        ->template();

// example
Chart::build('title',HorizontalBarChart::class)->labels([])->datasets([])

$barChart->datasets([
    Dataset::label('Task')->data([20, 30,55])->backgroundColor('yellow')
        ->borderColor('black')->make(),
    Dataset::label('Project')->data([50, 80,44])->backgroundColor('green')
        ->borderColor('white')->make(),
    Dataset::label('Issue')->data([70, 75,99])->backgroundColor('red')
        ->borderColor('white')->make(),
]);

$barChart->datasets(
    [
        [
            "label"           => "Task",
            "backgroundColor" => "yellow",
            "data"            => [20, 30,55],
            "borderColor"     => "yellow",
        ],
        [
            "label"           => "Project",
            "backgroundColor" => "green",
            "data"            => [50, 80,44],
            "borderColor"     => "green",
        ],
        [
            "label"           => "Issue",
            "backgroundColor" => "red",
            "data"            => [70, 75,99],
            "borderColor"     => "red",
        ],
    ]
);

// example
$barChart->changeDefaultOption('plugins.title.text','Monthly Project, Task And Issue Chart')
        ->changeDefaultOption('plugins.title.color','blue')

$barChart->options([
        'responsive' => false,
        'plugins'    => [
            'legend' => [
                'display'  => true,
                'position' => 'top',
            ],
            'title'  => [
                'text'     => 'Custom Title',
                'position' => 'top',
                'display'  => true,
                'color'    => 'black',
            ],
        ],
    ])

$barChart->options("{
        responsive : false,
        plugins    : {
            legend : {
                display  : true,
                position : 'top',
            },
            title  : {
                text     : 'Custom Title',
                position : 'top',
                display  : true,
                color    : 'black',
            },
        },
    }")

$barChart->size($height,$width = null)
html
<div class="chart">
    <!-- generate chart html canvas -->
    {!! $monthlyChart->chartHtml() !!}
</div>

......
<!-- generate chart js CDN scripts -->
{!! $monthlyChart->chartLibraries() !!}
<!-- generate chart configured scripts -->
{!! $monthlyChart->chartScripts() !!}