Laravel provides several database connection providers like sqlitemysqlpgsqlsqlsrv. In this tutorial, I will show you how to connect pgsql in laravel. If you do not know how to use postgresql with laravel, then this laravel postgresql tutorial is for you.

You have already known that 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 postgresql database in laravel 9.

.env

DB_CONNECTION=pgsql
DB_HOST=your_database_ip_address
DB_PORT=5432
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 the 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 Connect SQL Server Database In Laravel?

 

Conclusion

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