Chartjs-Laravel displaying a chart from another database connection

0👍

Let’s create a new database connection in config/database.php:

'connections' => [
    'mysql' => [
        // ....
    ],
    'mysql2' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST_SECOND', '127.0.0.1'),
        'port' => env('DB_PORT_SECOND', '3306'),
        'database' => env('DB_DATABASE_SECOND', 'forge'),
        'username' => env('DB_USERNAME_SECOND', 'forge'),
        'password' => env('DB_PASSWORD_SECOND', ''),
        // The followings are default Laravel settings, which could be redundant.
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => true,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ]
]

In the controller, you can say something like:

$chart = Charts::database(User::on('mysql2')->all(),'line','highcharts')
    ->title('User Statistics')
    ->groupByYear(7)
    ->Width(0)
    ->ElementLabel('Total Users Registered')
    ->Responsive(true);

return view('dashboard',['chart'=>$chart])->with('count', $count);

0👍

Updated answer from @Kevin Bui

'connections' => [
    'mysql' => [
        // ....
    ],
    'mysql2' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST_SECOND', '127.0.0.1'),
        'port' => env('DB_PORT_SECOND', '3306'),
        'database' => env('DB_DATABASE_SECOND', 'forge'),
        'username' => env('DB_USERNAME_SECOND', 'forge'),
        'password' => env('DB_PASSWORD_SECOND', ''),
        // The followings are default Laravel settings, which could be redundant.
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => true,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ]
]
In the controller, you can say something like:

$chart = Charts::database(User::on('mysql2')->all(),'line','highcharts')
    ->title('User Statistics')
    ->groupByYear(7)
    ->Width(0)
    ->ElementLabel('Total Users Registered')
    ->Responsive(true);

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

Leave a comment