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.
php -m | grep pdo_pgsql
sudo apt install php-pgsql
.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
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',
],
php artisan tinker >>> DB::connection()->getPdo();
use Illuminate\Support\Facades\DB;
Route::get('/db-check', function () {
return DB::connection()->getDatabaseName()
? 'PostgreSQL connected successfully!'
: 'Database connection failed!';
});
DB::transaction(function () {
DB::table('users')->insert([
'name' => 'Laravel User',
'email' => 'user@laravel.com',
'password' => bcrypt('password'),
]);
});
updating .env.
MySQL Example:
DB_CONNECTION=mysql DB_PORT=3306