Laravel provides several database connection providers like sqlitemysqlpgsqlsqlsrv. In this tutorial, I will show you how to connect mysql database in php laravel application.

Laravel provides a .env file in the project root path. We can connect any database configuration in laravel using this file. So let's see the example code of how to connect database in laravel 9 application:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_db_name_here
DB_USERNAME=your_db_username_here
DB_PASSWORD=your_db_password_here

 

Now you can check the connection using this below code:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;

class TutorialController extends Controller
{   
    public function index()
    {   
        try {
            $dbname = DB::connection()->getDatabaseName();
            return "Connected database name is: {$dbname}";
        } catch(\Exception $e) {
            return "Error in connecting to the database";
        }
    }
}

 

Read also: How To Check Database Connection In Laravel 9?

 

Conclusion

I have tried to discuss the clear concept of how to connect database in laravel. Now we know how to connect mysql database in php laravel. Hope this how to connect database in laravel 9 tutorial will help you.