How do I connect Laravel 7 to Microsoft SQL Server?

Viewed 8077

I'm really surprised the Laravel documentation is limited for explaining how to connect to MS SQL Server. There are two areas that I think need configuration -- the .env file and the database.php. Most examples on the web don't show the same format compared to Laravel 7. I would like to know where I can find the correct info for the following.

  • How to tell what port my DB is on
  • What to enter for URL
  • What to enter for HOST
  • When testing the connection it says 'driver not found' - is it saying the details are incorrect or is it looking for a missing file?
  • before changing the database.php file it has the word forge as the second argument for the env() function - what is forge???

If anyone can point me to a good resource id be in your debt!

DB_CONNECTION=sqlsrv
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test_db_1
DB_USERNAME=sa
DB_PASSWORD=mypassword
```

and the database.php...

    'default' => env('DB_CONNECTION', 'sqlsrv'), ...
...
 'sqlsrv' => [
            'driver' => 'sqlsrv',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'test_db_1'),
            'username' => env('DB_USERNAME', 'sa'),
            'password' => env('DB_PASSWORD', 'mypassword'),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],
1 Answers

Your DB_HOST will always be localhost, so if the database is on the same machine, 127.0.0.1 will be fine. TCP port 1433 is typically the port used by a default instance of SQL Server, set it to DB_PORT=1433.

Laravel Forge is a tool for deploying and configuring web applications and can be used to automate the deployment of any web application that uses a PHP server. Since we are using the .env to overwrite the values in config/database.php there is no need to worry about the "forge" values. Finally, you may need to install drivers on the machine to support PHP and SQL Server.

.env

DB_CONNECTION=sqlsrv
DB_HOST=127.0.0.1
DB_PORT=1433
DB_DATABASE=test_db_1
DB_USERNAME=sa
DB_PASSWORD=mypassword

config/database.php

'sqlsrv' => [
    'driver' => 'sqlsrv',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', '1433'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'prefix' => '',
    'prefix_indexes' => true,
]
Related