Loading...
+880 1736 699819 Mon - Sat: 9:00 AM - 8:00 PM
Follow us:
Home Blog Article
Blog

Connect Laravel with PostgreSQL Database Complete Guide with Example

Connect Laravel with PostgreSQL Database Complete Guide with Example

Laravel offers a powerful and flexible Laravel database connection system that supports both MySQL and PostgreSQL. While the Laravel MySQL connection is commonly used, PostgreSQL is widely chosen for high-performance and enterprise-level applications.

This tutorial explains how to connect Laravel with PostgreSQL database example, configure the Laravel PostgreSQL driver, verify connections using DB::connection, and safely manage queries using DB::transaction Laravel.

  • Advanced relational database support
  • Strong data consistency and ACID compliance
  • Native support via Laravel PostgreSQL driver
  • Easy configuration through Laravel database config file

Enable Laravel PostgreSQL Driver

php -m | grep pdo_pgsql

sudo apt install php-pgsql

Configure Laravel Database Connection

.env file:

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=laravel_pgsql_db
DB_USERNAME=postgres
DB_PASSWORD=secret

 Laravel Database Config File Setup

 config/database.php:

'pgsql' => [
    'driver' => 'pgsql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '5432'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'prefix' => '',
    'schema' => 'public',
    'sslmode' => 'prefer',
],

 Laravel Check DB::connection

php artisan tinker
>>> DB::connection()->getPdo();

 Route Test

use Illuminate\Support\Facades\DB;

Route::get('/db-check', function () {
    return DB::connection()->getDatabaseName()
        ? 'PostgreSQL connected successfully!'
        : 'Database connection failed!';
});

 Using DB::transaction in Laravel

DB::transaction(function () {
    DB::table('users')->insert([
        'name' => 'Laravel User',
        'email' => 'user@laravel.com',
        'password' => bcrypt('password'),
    ]);
});

Laravel PostgreSQL vs Laravel MySQL Connection

updating .env.

MySQL Example:

DB_CONNECTION=mysql
DB_PORT=3306
Tags: Blog
Share this post

Encoderbase Team

Author

Articles and insights from the Encoderbase editorial team covering web development, software engineering, and digital solutions.

Enjoyed this article?

Get more articles like this delivered to your inbox — no spam, unsubscribe any time.

Link copied to clipboard!