Last updated on November 29, 2023
To connect a Laravel application to an Azure SQL Server database, you’ll need to configure the database connection settings in your Laravel application. Here’s a step-by-step guide:
Step 1: Install Necessary Dependencies
Ensure you have the necessary database drivers installed. For Azure SQL Server, you’ll typically use the SQLSRV or PDO_SQLSRV drivers. You can install these using Composer:
For SQLSRV:
composer require microsoft/msphpsql
For PDO_SQLSRV:
composer require doctrine/dbal
composer require laravelcollective/remote
Step 2: Configure .env
File
In your Laravel project, locate the .env
file and set the database connection details. Modify the following fields:
DB_CONNECTION=sqlsrv
DB_HOST=your_server.database.windows.net
DB_PORT=1433
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
Replace your_server.database.windows.net
, your_database
, your_username
, and your_password
with your Azure SQL Server details.
Step 3: Database Configuration
In config/database.php
, make sure the database connections are correctly set up. The ‘connections’ array should contain the ‘sqlsrv’ configuration like this:
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'your_server.database.windows.net'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'your_database'),
'username' => env('DB_USERNAME', 'your_username'),
'password' => env('DB_PASSWORD', 'your_password'),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
],
Step 4: Enable TCP/IP in Azure Portal
Ensure that your Azure SQL Server instance allows connections over TCP/IP. You might need to configure the firewall settings in the Azure Portal to permit connections from your Laravel application’s server IP address.
Step 5: Test the Connection
After configuring, run a test to check if the Laravel application can connect to the Azure SQL Server database. You can do this by running a migration, seeding the database, or simply executing a query to verify the connection.
php artisan migrate
This command will run any pending migrations against the configured database connection.
Make sure to handle sensitive database credentials securely, especially in production environments, by using environment variables or other secure methods.
Remember to consult the latest Laravel and Azure documentation for any updates or changes related to database connections or Azure services.