Draw Charts with Laravel Charts package
Hey all! How are you? Doing fine? I think so. This time I brought you a different tutorial. It's about CHARTS! You may have seen some charts in web applications displaying some records. There are many types of charts. Ex: Bar charts, Line charts, Pie charts, Donut charts, Area charts....
I have been using Laravel framework for 6 months..I can say exactly, this is the best php framework I found! There's a lot of packages we can use for building applications easily. In this article also, I'm using a package built for drawing charts..
Now we can start the work! Follow the steps guys..
Step 1 - Create new laravel project
composer create-project laravel/laravel LaravelCharts
Step 2 - Migrate database
Open the project in a text editor and edit database configuration files.
Before database migration, we have something to do to avoid migration errors... In your project folder, open Http/Providers/AppServiceProvider.php file and replace its code with this.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
NOTE :
Delete the migrations in database/migrations built automatically called password resets and users. We don't need them. We are going to create a new model and a migration file. Open a command prompt/terminal and go into the project. Then type the below command to create a model.
php artisan make:model Product -m
Now there will a model called Product and a migration file made for products in database/migrations folder. Open the migration file to edit.
database/migrations/migration.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('prod_code');
$table->string('prod_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
Now we are ready to migrate our database. Then a table called products will be created. Command to migrate :
php artisan migrate
Go to PhpMyadmin or Mysql Workbench, see the results. Then insert some data to the database. Here is the SQL code to insert some data.
INSERT INTO `products` (`id`, `prod_code`, `prod_name`, `created_at`, `updated_at`) VALUES
(1, '1234', 'Product 1', '2018-08-07 20:23:23', NULL),
(2, '1235', 'Product 2', '2018-07-31 17:12:25', NULL),
(3, '3456', 'Product 3', '2018-07-16 16:12:19', NULL),
(4, '2345', 'Product 4', '2018-06-30 19:18:17', NULL),
(5, '6789', 'Product 5', '2018-06-02 22:20:12', NULL),
(6, '4567', 'Product 6', '2018-05-21 15:16:08', NULL),
(7, '2367', 'Product 7', '2018-05-05 09:20:15', NULL),
(8, '1236', 'Product 8', '2018-06-20 00:22:27', NULL),
(9, '3478', 'Product 9', '2018-03-31 04:50:20', NULL),
(10, '2756', 'Product 10', '2018-02-13 04:52:17', NULL);
Step 3 - Install Laravel Charts package into the project
Now it's time to install the Charts package. Open a terminal/cmd and go into the project folder. Type the below command and hit enter.
composer require consoletvs/charts:5.*
NOTE:
Don't install package version 6! It has some confusions!
php artisan make:controller ChartController
Add the index function to load the with products included in the database with a chart. First we will look for creating a BAR CHART! It it's working, then we can go for the other types of charts.
Key things to know :
title : Main title for the chart
elementLabel : Label for frequency axis for products
dimensions : width and height
colors : Colors for bars
groupByMonth() : Group the records by month
Open cmd or terminal and type php artisan serve. Then open web browser and type localhost:8000/charts to run see the charts. You will get this output in your browser.
We have done guys!
Since we gave the parameter bar to the database function is the controller function, we get a bar chart! How to get a pie chart? or line chart? Simple! This is the way,,
Change the word bar into the chart type you want. But you can only use the types defined in the package!
I think you have seen the difference! These are the main chart types we can use for representing data in an analytical form using charts!
These charts are very helpful when designing dashboards! Use them to display data.
So, now we have come to the end of the tutorial. I'll wrap up now! Try this with a large data set and see the results. It will a nice experience to you!
Good Bye guys!
NOTE:
Don't install package version 6! It has some confusions!
Then open config/app.php file to do further configurations.
Place this code in providers section
ConsoleTVs\Charts\ChartsServiceProvider::class,
Place this code in aliases section
'Charts' => ConsoleTVs\Charts\Facades\Charts::class,Place this code in providers section
ConsoleTVs\Charts\ChartsServiceProvider::class,
Place this code in aliases section
Step 4 - Create a controller to make charts
Open the cmd and type the command to create a controller called ChartController.php artisan make:controller ChartController
Add the index function to load the with products included in the database with a chart. First we will look for creating a BAR CHART! It it's working, then we can go for the other types of charts.
use App\Charts\SampleChart;
use Illuminate\Http\Request;
use App\Product;
use Charts;
use DB;
class ChartController extends Controller
{
public function index()
{
$products = Product::where(DB::raw("(DATE_FORMAT(created_at,'%Y'))"), date('Y'))->get();
$chart = Charts::database($products, 'bar', 'highcharts')
->title('Product Details')
->elementLabel('Total Products')
->dimensions(1000, 500)
->colors(['red', 'green', 'blue', 'yellow', 'orange', 'cyan', 'magenta'])
->groupByMonth(date('Y'), true);
return view('charts', ['chart' => $chart]);
}
}
Key things to know :
title : Main title for the chart
elementLabel : Label for frequency axis for products
dimensions : width and height
colors : Colors for bars
groupByMonth() : Group the records by month
Step 5 - Add Routes
Open routes/web.php and add this code lines.
Route::get('/', function () {
return view('welcome');
});
Route::get('charts', 'ChartController@index');
Step 6 - Create the view for charts
We need a chart view to display the charts. Now create a new view in resources/views folder. I will name it as charts.blade.php. Place this code!
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel Charts</title>
</head>
<body>
<div class="container">
<h1 style="text-align: center;">Charts with Laravel</h1>
<br>
{!! $chart->html() !!}
</div>
{!! Charts::scripts() !!}
{!! $chart->script() !!}
</body>
</html>
Open cmd or terminal and type php artisan serve. Then open web browser and type localhost:8000/charts to run see the charts. You will get this output in your browser.
We have done guys!
Since we gave the parameter bar to the database function is the controller function, we get a bar chart! How to get a pie chart? or line chart? Simple! This is the way,,
Change the word bar into the chart type you want. But you can only use the types defined in the package!
Pie Chart
$products = Product::where(DB::raw("(DATE_FORMAT(created_at,'%Y'))"), date('Y'))->get();
$chart = Charts::database($products, 'pie', 'highcharts')
->title('Product Details')
->elementLabel('Total Products')
->dimensions(1000, 500)
->colors(['red', 'green', 'blue', 'yellow', 'orange', 'cyan', 'magenta'])
->groupByMonth(date('Y'), true);
return view('charts', ['chart' => $chart]);
Line Chart
$products = Product::where(DB::raw("(DATE_FORMAT(created_at,'%Y'))"), date('Y'))->get();
$chart = Charts::database($products, 'pie', 'highcharts')
->title('Product Details')
->elementLabel('Total Products')
->dimensions(1000, 500)
->groupByMonth(date('Y'), true);
return view('charts', ['chart' => $chart]);
Area Chart
$products = Product::where(DB::raw("(DATE_FORMAT(created_at,'%Y'))"), date('Y'))->get();
$chart = Charts::database($products, 'pie', 'highcharts')
->title('Product Details')
->elementLabel('Total Products')
->dimensions(1000, 500)
->groupByMonth(date('Y'), true);
return view('charts', ['chart' => $chart]);
Donut Chart
$products = Product::where(DB::raw("(DATE_FORMAT(created_at,'%Y'))"), date('Y'))->get();
$chart = Charts::database($products, 'pie', 'highcharts')
->title('Product Details')
->elementLabel('Total Products')
->dimensions(1000, 500)
->colors(['red', 'green', 'blue', 'yellow', 'orange', 'cyan', 'magenta'])
->groupByMonth(date('Y'), true);
return view('charts', ['chart' => $chart]);
I think you have seen the difference! These are the main chart types we can use for representing data in an analytical form using charts!
These charts are very helpful when designing dashboards! Use them to display data.
So, now we have come to the end of the tutorial. I'll wrap up now! Try this with a large data set and see the results. It will a nice experience to you!
Good Bye guys!
14 Comments
awesome, thanks you
ReplyDeleteThank You Quan!
Deletegood job
ReplyDeletethnx!!!!!!
Thank you!
DeleteNice job , we are also Laravel Development Company for any free help contact us.
ReplyDeleteThanks for your idea ExpressTech!
Deletei found this error :Undefined variable: chart (0)
ReplyDeleteafter following above step plz give me a reply
Sorry for the delay I was busy..i hope now you have solved your problem..
Deletei have a same
DeleteLaravel Development Company, Laravel is among the best PHP-based web app framework that is free and open-source. We offers a robust team of Laravel developers and programmers offering high-end and reliable solutions at highly-competitive rates. Contact us : +91-9806724185 or Contact@expresstechsoftwares.com
ReplyDeleteNice tutorial but its missing some explanations of a few things. I'm looking at the line chart. The labels show the dates in M, Y format, yet I don't see anything in the chart parameters that set it to that format. All I see is date('Y'). Could you please provide more details on the chart parameters?
ReplyDeletevery nice tutorial
ReplyDeleteHow to change X-axis and Y-axis name ????
ReplyDeleteSatsport is your ultimate destination for cutting-edge sports insights and services in India. Offering a seamless platform for sports enthusiasts, we specialize in delivering real-time updates, secure transactions, and an unmatched user experience. Discover the best of sports engagement with Satsports today!"
ReplyDelete