Laravel Users, Here's How to Find Your Database Size!

 How to get Database size in Laravel - PHP

Laravel-Users-Here's-How-to-Find-Your-Database-Size

PHP provides lots of methods to make our development more faster and easier . In this article we will learn how can you calculate your database size in your Laravel project or in your PHP project . It's super easy , you just have to write some PHP raw queries in order to achieve this .

In this example i will show you how to calculate to your connected database size in a Laravel project but you can use this example in your php project too .

Step 1 - Connect to a database :-

Before calculating database size make sure that you are connected to a database , here my laravel project connected to a database named " laraveldemo " as you can see my " .env " file below .

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldemo
DB_USERNAME=root
DB_PASSWORD=

Step 2 - Calculate DB size :-

Now you can use the following piece of code in your project to calculate your database size . Make sure to put the database name on the code below instead of " laraveldemo " .

Get Database size in KB :-

public function getDBSizeInKB()
    {
         $result = DB::select(DB::raw('SELECT table_name AS "Table",
                ((data_length + index_length) / 1024) AS "Size"
                FROM information_schema.TABLES
                WHERE table_schema ="'.'laraveldemo'. '"
                ORDER BY (data_length + index_length) DESC'));
            $size = array_sum(array_column($result, 'Size'));
            $db_size = number_format((float)$size, 2, '.', '');
            dd($db_size);

    }

Output :-

"144.00"


Get Database size in MB:-

public function getDBSizeInMB()
    {
         $result = DB::select(DB::raw('SELECT table_name AS "Table",
                ((data_length + index_length) / 1024 / 1024) AS "Size"
                FROM information_schema.TABLES
                WHERE table_schema ="'.'laraveldemo'. '"
                ORDER BY (data_length + index_length) DESC'));
            $size = array_sum(array_column($result, 'Size'));
            $db_size = number_format((float)$size, 2, '.', '');
            dd($db_size);

    }

Output :-

"0.14"


Previous Post Next Post

Contact Form