• Stars
    star
    460
  • Rank 95,202 (Top 2 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Package to draw charts in Laravel with Chart.js

Laravel Charts

Package to generate Chart.js charts directly from Laravel/Blade, without interacting with JavaScript.


Simple Usage

Laravel Charts - Users by Months

If you want to generate a chart above, grouping users records by the month of created_at value, here's the code.

Controller:

use LaravelDaily\LaravelCharts\Classes\LaravelChart;

// ...

$chart_options = [
    'chart_title' => 'Users by months',
    'report_type' => 'group_by_date',
    'model' => 'App\Models\User',
    'group_by_field' => 'created_at',
    'group_by_period' => 'month',
    'chart_type' => 'bar',
];
$chart1 = new LaravelChart($chart_options);

return view('home', compact('chart1'));

View File

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Dashboard</div>

                <div class="card-body">

                    <h1>{{ $chart1->options['chart_title'] }}</h1>
                    {!! $chart1->renderHtml() !!}

                </div>

            </div>
        </div>
    </div>
</div>
@endsection

@section('javascript')
{!! $chart1->renderChartJsLibrary() !!}
{!! $chart1->renderJs() !!}
@endsection

Installation

composer require laraveldaily/laravel-charts

No additional configuration or other parameters yet.


Usage

You need to create LaravelChart object in your Controller, passing array of options.

$chart = new LaravelChart($options);

Then pass it to the View, as a variable:

return view('dashboard', compact('chart'));

Available Reports and Options

Currently package support three types of charts/reports:

  • group_by_date - amount of records from the same table, grouped by time period - day/week/month/year;
  • group_by_string - amount of records from the same table, grouped by any string field, like name;
  • group_by_relationship - amount of records from the same table, grouped by belongsTo relationship's field

NOTE: From Laravel 8, all its models are placed in a folder called Models (App\Models)

Example with all options

$chart_options = [
    'chart_title' => 'Transactions by dates',
    'chart_type' => 'line',
    'report_type' => 'group_by_date',
    'model' => 'App\Models\Transaction',
    'conditions'            => [
        ['name' => 'Food', 'condition' => 'category_id = 1', 'color' => 'black', 'fill' => true],
        ['name' => 'Transport', 'condition' => 'category_id = 2', 'color' => 'blue', 'fill' => true],
    ],

    'group_by_field' => 'transaction_date',
    'group_by_period' => 'day',

    'aggregate_function' => 'sum',
    'aggregate_field' => 'amount',
    'aggregate_transform' => function($value) {
        return round($value / 100, 2);
    },
    
    'filter_field' => 'transaction_date',
    'filter_days' => 30, // show only transactions for last 30 days
    'filter_period' => 'week', // show only transactions for this week
    'continuous_time' => true, // show continuous timeline including dates without data
];
  • chart_title (required) - just a text title that will be shown as legend;
  • chart_type (required) - possible values: "line", "bar", "pie";
  • report_type (required) - see above, can be group_by_date, group_by_string or group_by_relationship;
  • model (required) - name of Eloquent model, where to take the data from;
  • name (optional) - just a text title that will be shown as title, otherwise the legend is used;
  • conditions (optional, only for line chart type) - array of conditions (name + raw condition + color) for multiple datasets;
  • group_by_field (required) - name of database field that will be used in group_by clause;
  • group_by_period (optional, only for group_by_date report type) - possible values are "day", "week", "month", "year";
  • relationship_name (optional, only for group_by_relationship report type) - the name of model's method that contains belongsTo relationship.
  • aggregate_function (optional) - you can view not only amount of records, but also their SUM() or AVG(). Possible values: "count" (default), "avg", "sum".
  • aggregate_field (optional) - see aggregate_function above, the name of the field to use in SUM() or AVG() functions. Irrelevant for COUNT().
  • aggregate_transform (optional) - callback function for additional transformation of aggregate number
  • filter_field (optional) - show only data filtered by that datetime field (see below)
  • filter_days (optional) - see filter_field above - show only last filter_days days of that field. Example, last 30 days by created_at field.
  • filter_period (optional) - another way to filter by field, show only record from last week / month / year. Possible values are "week", "month", "year".
  • continuous_time (optional) - show all dates on chart, including dates without data.
  • show_blank_data (optional) - show date even if the data is blank based on filter_days.
  • range_date_start (optional) - show data in from a date range by filter_field, this is the start date.
  • range_date_end (optional) - show data in from a date range by filter_field, this is the end date.
  • field_distinct (optional) - field name required, it will apply a distinct(fieldname)
  • style_class (optional) - add class css in canvas
  • date_format (optional) - add the date format, by default: American format Y-m-d
  • where_raw (optional) - Condition in multiple consultation situations
  • chart_height (optional) - add the height in options, default 300px
  • date_format_filter_days (optional) - add the date format for Filter days
  • withoutGlobalScopes (optional) - removes global scope restriction from queried model
  • with_trashed (optional) - includes soft deleted models
  • only_trashed (optional) - only displays soft deleted models
  • top_results (optional, integer) - limit number of results shown, see Issue #49
  • chart_color (optional, value in rgba, like "0,255,255") - defines the color of the chart
  • labels (optional, array with key and value) - defines key value array mapping old and new values
  • hidden (optional, boolean) hides the current dataset. Useful when having multiple datasets in one chart
  • stacked (optional, boolean, only for bar chart) stacks the chart data when dates or strings match instead of showing it next to eachother

Example with relationship

$chart_options = [
    'chart_title' => 'Transactions by user',
    'chart_type' => 'line',
    'report_type' => 'group_by_relationship',
    'model' => 'App\Models\Transaction',

    'relationship_name' => 'user', // represents function user() on Transaction model
    'group_by_field' => 'name', // users.name

    'aggregate_function' => 'sum',
    'aggregate_field' => 'amount',
    
    'filter_field' => 'transaction_date',
    'filter_days' => 30, // show only transactions for last 30 days
    'filter_period' => 'week', // show only transactions for this week
];

Rendering Charts in Blade

After you passed $chart variable, into Blade, you can render it, by doing three actions:

Action 1. Render HTML.

Wherever in your Blade, call this:

{!! $chart1->renderHtml() !!}

It will generate something like this:

<canvas id="myChart"></canvas>

Action 2. Render JavaScript Library

Package is using Chart.js library, so we need to initialize it somewhere in scripts section:

{!! $chart1->renderChartJsLibrary() !!}

It will generate something like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>

Action 3. Render JavaScript of Specific Chart

After Chart.js is loaded, launch this:

{!! $chart1->renderJs() !!}

Using Multiple Charts

You can show multiple charts on the same page, initialize them separately.

Controller:

public function index()
{
    $chart_options = [
        'chart_title' => 'Users by months',
        'report_type' => 'group_by_date',
        'model' => 'App\Models\User',
        'group_by_field' => 'created_at',
        'group_by_period' => 'month',
        'chart_type' => 'bar',
        'filter_field' => 'created_at',
        'filter_days' => 30, // show only last 30 days
    ];

    $chart1 = new LaravelChart($chart_options);


    $chart_options = [
        'chart_title' => 'Users by names',
        'report_type' => 'group_by_string',
        'model' => 'App\Models\User',
        'group_by_field' => 'name',
        'chart_type' => 'pie',
        'filter_field' => 'created_at',
        'filter_period' => 'month', // show users only registered this month
    ];

    $chart2 = new LaravelChart($chart_options);

    $chart_options = [
        'chart_title' => 'Transactions by dates',
        'report_type' => 'group_by_date',
        'model' => 'App\Models\Transaction',
        'group_by_field' => 'transaction_date',
        'group_by_period' => 'day',
        'aggregate_function' => 'sum',
        'aggregate_field' => 'amount',
        'chart_type' => 'line',
    ];

    $chart3 = new LaravelChart($chart_options);

    return view('home', compact('chart1', 'chart2', 'chart3'));
}

View:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Dashboard</div>

                <div class="card-body">

                    <h1>{{ $chart1->options['chart_title'] }}</h1>
                    {!! $chart1->renderHtml() !!}

                <hr />

                    <h1>{{ $chart2->options['chart_title'] }}</h1>
                    {!! $chart2->renderHtml() !!}

                    <hr />

                    <h1>{{ $chart3->options['chart_title'] }}</h1>
                    {!! $chart3->renderHtml() !!}

                </div>

            </div>
        </div>
    </div>
</div>
@endsection

@section('javascript')
{!! $chart1->renderChartJsLibrary() !!}

{!! $chart1->renderJs() !!}
{!! $chart2->renderJs() !!}
{!! $chart3->renderJs() !!}
@endsection

Laravel Charts - Users by Months

Laravel Charts - Users by Names

Laravel Charts - Transactions by Dates


Multiple Datasets

This is a new feature from v0.1.27. You can provide multiple arrays of settings to the LaravelChart constructor, and they will be drawn on the same chart.

$settings1 = [
    'chart_title'           => 'Users',
    'chart_type'            => 'line',
    'report_type'           => 'group_by_date',
    'model'                 => 'App\Models\User',
    'group_by_field'        => 'created_at',
    'group_by_period'       => 'day',
    'aggregate_function'    => 'count',
    'filter_field'          => 'created_at',
    'filter_days'           => '30',
    'group_by_field_format' => 'Y-m-d H:i:s',
    'column_class'          => 'col-md-12',
    'entries_number'        => '5',
    'translation_key'       => 'user',
    'continuous_time'       => true,
];
$settings2 = [
    'chart_title'           => 'Projects',
    'chart_type'            => 'line',
    'report_type'           => 'group_by_date',
    'model'                 => 'App\Models\Project',
    // ... other values identical to $settings1
];

$chart1 = new LaravelChart($settings1, $settings2);

Multiple Datasets


License

The MIT License (MIT). Please see License File for more information.


More from our LaravelDaily Team

More Repositories

1

laravel-tips

Awesome tips for Laravel
6,267
star
2

Laravel-Roadmap-Learning-Path

5,264
star
3

laravel-invoices

Laravel package to generate PDF invoices from various customizable parameters
PHP
1,341
star
4

Larastarters

SCSS
753
star
5

laravel-roles-permissions-manager

Laravel 6 adminpanel starter boilerplate project with roles-permissions management.
PHP
654
star
6

quickadmin

Quick adminpanel builder package for Laravel 5
CSS
602
star
7

Best-Laravel-Packages

398
star
8

Laravel-Support-Ticketing

Laravel 6 Project for Support Tickets. Partly generated with QuickAdminPanel.
PHP
255
star
9

Laravel-Vue-First-CRUD

Simple demo project for Laravel 5.5 and Vue.js with one CRUD operation.
PHP
254
star
10

Laravel-Passport-API-Server-Client-Demo

Demo project to show how Laravel Passport works - we have both Server and Client here.
HTML
228
star
11

Laraquiz-QuickAdminPanel

Laravel 5.6 based quiz system - generated with QuickAdmin https://quickadminpanel.com
CSS
222
star
12

FilaStart

PHP
217
star
13

Hotel-Booking

Laravel 5.5 Demo-project for booking hotel rooms, mostly generated with https://quickadminpanel.com
HTML
176
star
14

laravel-roles-permissions-bouncer

Laravel 6 adminpanel starter boilerplate project with roles-permissions based on Bouncer package.
PHP
173
star
15

Laravel-School-Timetable-Calendar

Laravel 6 demo project for school timetable. Partly generated with https://quickadminpanel.com
PHP
171
star
16

Laravel-Appointments

Laravel 6 demo project for appointments management. Generated with https://2019.quickadminpanel.com.
PHP
153
star
17

Laravel-Asset-Stock-Management

Laravel 7 demo project for managing stock in multiple hospitals. Partly generated with https://quickadminpanel.com
PHP
152
star
18

QuickLMS

Simple Learning Management System based on Laravel 5.4.
HTML
140
star
19

Laravel-Vue-Login-Register

Demo-project of Laravel Login/Register via API from Vue.js client
PHP
140
star
20

Larancer-QuickAdminPanel

Laravel 5.5 system for freelancers to manage their clients/projects/income - generated with QuickAdmin
JavaScript
137
star
21

Laravel-Datatables-Advanced

A few advanced examples of Laravel + Datatables.net
PHP
127
star
22

Laravel-Jetstream-CRUD-Roles

PHP
127
star
23

Laravel-AdminLTE3-Boilerplate

Boilerplate adminpanel: Laravel 6.0 + AdminLTE 3 (Bootstrap 4) and simple CRUD examples. Based on new QuickAdminPanel 2019.
PHP
119
star
24

Test-Laravel-Routes

PHP
116
star
25

Laravel-Import-CSV-Demo

Small demo project to import CSV in Laravel 5.5 with matching the columns.
PHP
112
star
26

LaraAppointments-QuickAdminPanel

Laravel 5.5 based appointment-management system created with QuickAdminPanel https://quickadminpanel.com
JavaScript
109
star
27

Laravel-Roadmap-Beginner-Challenge

109
star
28

Laravel-Event-Conference-Demo

Laravel 6 demo project to manage conference/event data. Adminpanel generated with https://2019.quickadminpanel.com
PHP
105
star
29

Laravel-CoreUI-AdminPanel

Boilerplate adminpanel: Laravel 6.0 + CoreUI Theme (Bootstrap 4) and simple CRUD examples. Based on new QuickAdminPanel 2019.
PHP
102
star
30

Laravel-Checklister

PHP
96
star
31

Laravel-File-Storage

Laravel 5.5 Demo-project to store files, mini-Dropbox with multi-tenancy and Stripe payments.
HTML
96
star
32

QuickAdminPanel-Freelancer-CRM

Laravel 6 demo project for freelancers to manage their projects and income. Generated with https://2019.quickadminpanel.com
PHP
92
star
33

api-generator

API Generator for Laravel 5
PHP
87
star
34

Larancer-Vue

Vue+Laravel panel to manage freelancer's projects/income. Generated with our QuickAdminPanel.
HTML
86
star
35

Laravel-Demo-Courses-Enrollment

Demo Laravel project (task from Upwork) for students to register for courses from various universities.
PHP
86
star
36

Laravel-Real-Estate-Venue-Portal

Laravel 6 Real Estate demo-project based on Bootstrap theme
HTML
83
star
37

Laravel-Vue-Sidebar-Filters

Demo-project with Laravel API and Vue.js - Sidebar Filters for Catalog/E-Shop
PHP
83
star
38

laravel-permission-ui

Blade
82
star
39

Laravel-Shops-Map-QuickAdminPanel

Laravel 6 demo project for shops map. Adminpanel generated with https://quickadminpanel.com
PHP
81
star
40

Laravel-Vue-Employees-Adminpanel

Laravel + Vue.js Demo-project generated with our generator https://vue.quickadminpanel.com
HTML
80
star
41

Vue-Laravel-SPA-Boilerplate

PHP
78
star
42

Laravel-Vue-3-Composition-API-CRUD

PHP
77
star
43

QuickAdminPanel-Tailwind

PHP
75
star
44

Laravel-SOLID-Course-Examples

PHP
75
star
45

Laravel-Restaurant-Menu

Laravel demo-project: manage restaurant menu with reordering positions. Partly generated with https://quickadminpanel.com
PHP
75
star
46

Laravel-Job-Listings-QuickAdminPanel

Laravel 6 demo project for job listings directory. Adminpanel generated with https://2019.quickadminpanel.com
PHP
75
star
47

Laravel-KnowledgeBase-FAQ

Laravel 6 demo project to manage FAQ Knowledge Base. Adminpanel generated with https://2019.quickadminpanel.com
PHP
73
star
48

Laravel-Roadmap-Advanced-Beginner-Challenge

72
star
49

Test-Laravel-Blade-Basics

PHP
71
star
50

Laravel-Classimax-Directory

Demo project of Laravel simple classifieds list based on front-end theme Classimax.
HTML
70
star
51

Laravel-Breeze-Pages-Skeleton

PHP
67
star
52

Laravel-Loan-Management-Demo

PHP
67
star
53

Livewire-Parent-Child-Master-Detail

PHP
64
star
54

LaraEventTickets-QuickAdminPanel

Laravel 5.4 based simple event tickets admin + page created with QuickAdminPanel https://quickadminpanel.com
HTML
64
star
55

Test-Laravel-Auth-Basics

PHP
64
star
56

Laravel-Auth-Invitations

Demo project of Laravel 5.5 Auth extended so that only invited users can register.
PHP
63
star
57

Laravel-Adminator-QuickAdminPanel

Simple Laravel adminpanel based on Adminator theme, partly generated with QuickAdminPanel
PHP
63
star
58

Test-Laravel-Eloquent-Basics

PHP
62
star
59

Laravel-Faculty-RoomBooking

Laravel 7 Demo Project for Room Booking with Stripe. Generated with https://quickadminpanel.com and CoreUI theme.
PHP
62
star
60

Laravel-Admin-User-Layouts

PHP
61
star
61

Laravel-Job-Board-Demo

Demo Job Board project with Laravel 5.8. Partly generated with our QuickAdminPanel 2019.
PHP
61
star
62

QuickAdminPanel-ExpenseManager

Laravel 6 Demo project: Expense manager with multi-tenancy registration. Generated with https://2019.quickadminpanel.com
PHP
60
star
63

Laravel-Multi-Domain-Tenancy-Shops

Example Laravel 6 Project to have sub-domains for companies. Partly created with QuickAdminPanel.
PHP
60
star
64

Test-Laravel-File-Upload

PHP
58
star
65

Laravel-Envoyer-SaaS-Generator

Laravel 7 Demo Project re-creating Envoyer plans structure. Generated with SaaS Generator at https://quickadminpanel.com
PHP
58
star
66

Laravel-Demo-Support-Tickets

PHP
57
star
67

Laravel-Two-Factor-Auth-Email

PHP
57
star
68

Laravel-Test-Result-PDF

Laravel Quiz/Test Project with PDF Results. Adminpanel generated with https://www.quickadminpanel.com
PHP
56
star
69

Laravel-Datatables-Demo

Simple demo project for Datatables.net in Laravel 5.5 - with default and server-side rendering.
PHP
55
star
70

Laravel-AmazonS3-Video

Demo project of uploading video file to Amazon S3 with Laravel+AJAX
HTML
55
star
71

Laravel-Excel-Export-Import-Large-Files

PHP
54
star
72

Test-Eloquent-Relationships

PHP
54
star
73

Laravel-Login-Activity-Dashboard

Demo-project with dashboard on how many users logged in recently. Partly generated with QuickAdminPanel 2019.
PHP
53
star
74

Laravel-Vue-SPA-Vuetify

PHP
51
star
75

QuickAdminPanel-Material-Dashboard

Simple Laravel adminpanel based on Material Dashboard theme from Creative Tim
PHP
51
star
76

Laravel-Vue3-CRUD-Course-2022

PHP
51
star
77

Laravel-SaaS-Subscriptions-Demo

PHP
51
star
78

Laravel-Mobile-Phone-Verification-Demo

PHP
50
star
79

Test-Laravel-Migrations

PHP
50
star
80

Laravel-Filament-Admin-Course

JavaScript
49
star
81

Laravel-useful-seeds

Some migrations/seeds and data that may be useful for various Laravel projects
PHP
48
star
82

Laravel-Notifications-Database

Laravel Notifications Example with Database Driver
PHP
48
star
83

Laravel-OpenAPI-Swagger-Documentation-Example

Laravel documentation example with OpenAPI (ex. Swagger)
PHP
47
star
84

Landlord-Tenants-Laravel

Laravel 5.6 Demo-project where landlords and tenants can exchange documents/notes/messages.
HTML
47
star
85

Test-Laravel-Validation

PHP
46
star
86

Laravel-Jetstream-MultiAuth-Roles

PHP
46
star
87

Laravel-Multi-Level-Categories-Eshop

PHP
45
star
88

ExpenseManager

Laravel 5.5 Demo project - Expense manager with multi-tenancy registration. Partly generated by https://quickadminpanel.com
HTML
44
star
89

Laravel-API-Vue-Catalog

Demo-project with Laravel API and Vue.js
PHP
43
star
90

Laravel-Roadmap-Advanced-Beginner-Roadmap

PHP
42
star
91

Laravel-SaaS-Demo-Project

PHP
42
star
92

tutorials-api-auth

PHP
41
star
93

Livewire-jQuery-Three-Dropdowns

PHP
40
star
94

laravel-permission-editor

Visual UI for managing Roles/Permissions for Spatie Laravel Permission package
Blade
40
star
95

Laravel-8-Import-CSV

PHP
40
star
96

QuickAdminPanel-Livewire-Tailwind-Example

PHP
39
star
97

QuickInvitations

Simple Event Invitations System based on Laravel 5.5. Partly created with https://quickadminpanel.com
HTML
38
star
98

Laravel-8-Fortify-Bootstrap-Demo

PHP
37
star
99

Laravel-Room-Booking-Filters

Demo-project for managing bookings at hotels and rooms.
PHP
37
star
100

Laravel-Todoist-SaaS

PHP
36
star