Skip to content

Charts With Eloquent

Here is a guide to create factory, seeders to set data and create a chart rendering that data.

Add User factory

php
public function run()
{
    \App\Models\User::factory()->times(100)->create();
}

Run the seeder

In your command line:

php
php artisan migrate:fresh --seed

Pie chart using eloquent

In your command line:

bash
php artisan make:chart MonthlyUsersChart

On app/Charts/MonthlyUsersChart.php

php
return $this->chart->pieChart()
    ->setTitle('Monthly Users')
    ->addData([
        \App\Models\User::where('id', '<=', 60)->count(),
        \App\Models\User::where('id', '>', 60)->count()
    ])
    ->setColors(['#ffc63b', '#ff6384'])
    ->setLabels(['Active users', 'Inactive users']);

Line chart using eloquent

On app/Charts/MonthlyUsersChart.php

Replace the pieChart for lineChart method:

php
return $this->chart->lineChart()
    ->setTitle('Monthly Users')
    ->addData(\App\Models\User::query()->inRandomOrder()->limit(6)->pluck('id')->toArray(), 'Active users')
    ->addData(\App\Models\User::query()->inRandomOrder()->limit(6)->pluck('id')->toArray(), 'Inactive users')
    ->setXAxis(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'])
    ->setColors(['#ffc63b', '#ff6384']);