How to Connect Laravel to SQL Server (Windows, XAMPP and Linux)

Laravel is usually paired with MySQL, but plenty of companies keep their real data in SQL Server: the ERP, the accounting system, the HR database. Sooner or later someone asks for a web portal on top of it, and the Laravel developer gets the job.

Laravel supports SQL Server out of the box. The hard part is never the Laravel code; it’s getting PHP to talk to SQL Server in the first place: the right driver files, the ODBC driver, TCP/IP, and the certificate error that ODBC Driver 18 throws at almost everyone. This guide walks through it step by step on Windows (including XAMPP) and Linux, then shows how to use SQL Server alongside MySQL in the same app and call stored procedures.

Chain from Laravel through the pdo_sqlsrv PHP extension and ODBC Driver 18 to SQL Server on port 1433, with common connection errors and a second erp connection

What you need

Three pieces have to line up:

  1. Microsoft ODBC Driver for SQL Server (version 17 or 18) installed on the machine running PHP.
  2. Microsoft Drivers for PHP for SQL Server: the PHP extensions sqlsrv and pdo_sqlsrv. Laravel uses pdo_sqlsrv.
  3. SQL Server accepting TCP/IP connections, with a login for the app.

Most connection problems come from a mismatch in steps 1 and 2: wrong PHP version, wrong thread-safety build, or no ODBC driver.

Step 1: prepare SQL Server

In SQL Server Configuration Manager:

  • Under SQL Server Network Configuration > Protocols for [instance], set TCP/IP to Enabled. It’s disabled by default on Express and Developer editions.
  • For a fixed port, open TCP/IP properties > IP Addresses > IPAll and set TCP Port to 1433 (and clear TCP Dynamic Ports).
  • Restart the SQL Server service.
  • Open port 1433 in Windows Firewall if PHP runs on another machine.

In SSMS, make sure SQL Server and Windows Authentication mode is enabled (Server properties > Security), then create a login for the web app with only the permissions it needs:

CREATE LOGIN laravel_app WITH PASSWORD = 'Use-A-Long-Random-Password-1!';
USE ErpDB;
CREATE USER laravel_app FOR LOGIN laravel_app;
ALTER ROLE db_datareader ADD MEMBER laravel_app;
-- Add db_datawriter, or GRANT EXECUTE on specific procedures, only if the portal must change data

Don’t connect a web app as sa.

Step 2: install the drivers on Windows (XAMPP or plain PHP)

ODBC driver. Download and install Microsoft ODBC Driver 18 for SQL Server (x64) from Microsoft.

PHP extensions. Check your PHP version and build:

php -v
php -i | findstr "Thread"

You need the DLLs that match both the version (8.2, 8.3…) and the build: XAMPP’s Apache uses the thread-safe (TS) build, x64. Download Microsoft Drivers for PHP for SQL Server, extract it, and copy the two matching files to C:\xampp\php\ext, for example:

php_sqlsrv_83_ts_x64.dll
php_pdo_sqlsrv_83_ts_x64.dll

Add them to C:\xampp\php\php.ini:

extension=php_sqlsrv_83_ts_x64.dll
extension=php_pdo_sqlsrv_83_ts_x64.dll

Restart Apache. Then check both places PHP runs, because the command line and Apache can use different php.ini files:

php -m | findstr sqlsrv

and a temporary phpinfo() page in the browser (search for “pdo_sqlsrv”; delete the page afterwards).

Step 2 (Linux alternative)

On Ubuntu or Debian, install Microsoft’s msodbcsql18 package from Microsoft’s repository (follow their current instructions for your distribution version), then:

sudo apt-get install unixodbc-dev php8.3-dev php-pear
sudo pecl install sqlsrv pdo_sqlsrv
echo "extension=sqlsrv.so"     | sudo tee /etc/php/8.3/mods-available/sqlsrv.ini
echo "extension=pdo_sqlsrv.so" | sudo tee /etc/php/8.3/mods-available/pdo_sqlsrv.ini
sudo phpenmod sqlsrv pdo_sqlsrv
sudo systemctl restart php8.3-fpm   # or apache2

Step 3: configure Laravel

In .env:

DB_CONNECTION=sqlsrv
DB_HOST=192.168.1.20
DB_PORT=1433
DB_DATABASE=ErpDB
DB_USERNAME=laravel_app
DB_PASSWORD=Use-A-Long-Random-Password-1!

config/database.php already has a sqlsrv connection that reads these values. Add two settings to it (they may be there commented out):

'sqlsrv' => [
    'driver' => 'sqlsrv',
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', '1433'),
    'database' => env('DB_DATABASE', 'laravel'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => env('DB_CHARSET', 'utf8'),
    'prefix' => '',
    'prefix_indexes' => true,
    'encrypt' => env('DB_ENCRYPT', 'yes'),
    'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],

Named instance (like SQLEXPRESS) on a dynamic port: put the instance in the host and leave the port empty, and make sure the SQL Server Browser service is running:

DB_HOST=192.168.1.20\SQLEXPRESS
DB_PORT=

Test the connection:

php artisan db:show

or in php artisan tinker:

DB::select('SELECT @@VERSION AS v');

The certificate error (ODBC Driver 18)

The most common error after a correct setup is:

SQLSTATE[08001]: [Microsoft][ODBC Driver 18 for SQL Server]SSL Provider:
The certificate chain was issued by an authority that is not trusted.

ODBC Driver 18 encrypts connections by default and checks the server’s certificate. A default SQL Server install uses a self-signed certificate, which isn’t trusted. You have two options:

  • Proper fix (production): install a certificate from a trusted authority on SQL Server, so encryption is checked end to end.
  • Internal network, development: keep encryption but trust the server’s certificate:
DB_ENCRYPT=yes
DB_TRUST_SERVER_CERTIFICATE=true

Run php artisan config:clear after changing .env if you use config caching. Avoid turning encryption off entirely: the connection would carry passwords and data in plain text.

Other errors and what they mean

ErrorUsual cause
could not find driverpdo_sqlsrv not loaded in this PHP (check php -m and the right php.ini)
This extension requires the Microsoft ODBC Driver for SQL ServerODBC driver not installed, or the wrong one (32-bit)
TCP Provider: No connection could be made... / Login timeout expiredTCP/IP disabled, wrong port, firewall, or SQL Server Browser stopped for a named instance
Login failed for user 'laravel_app'Wrong password, SQL authentication not enabled, or the user wasn’t created in that database
The certificate chain was issued by an authority that is not trustedSee the section above

Using SQL Server alongside MySQL

A common setup: the Laravel app keeps its own tables (users, sessions, jobs) in MySQL and reads business data from the company’s SQL Server. Keep MySQL as the default and add a second connection:

// config/database.php, inside 'connections'
'erp' => [
    'driver' => 'sqlsrv',
    'host' => env('ERP_DB_HOST'),
    'port' => env('ERP_DB_PORT', '1433'),
    'database' => env('ERP_DB_DATABASE'),
    'username' => env('ERP_DB_USERNAME'),
    'password' => env('ERP_DB_PASSWORD'),
    'charset' => 'utf8',
    'prefix' => '',
    'encrypt' => env('ERP_DB_ENCRYPT', 'yes'),
    'trust_server_certificate' => env('ERP_DB_TRUST_SERVER_CERTIFICATE', 'false'),
],

Point a model at it:

class Customer extends Model
{
    protected $connection = 'erp';
    protected $table = 'dbo.Customers';
    protected $primaryKey = 'CustomerID';
    public $timestamps = false;   // ERP tables rarely have created_at / updated_at
}

Or use the query builder:

$invoices = DB::connection('erp')
    ->table('dbo.Invoices')
    ->where('CustomerID', $customerId)
    ->orderByDesc('InvoiceDate')
    ->paginate(25);

Pagination works normally; Laravel generates OFFSET ... FETCH for SQL Server 2012 and later.

You can’t join tables across the two connections in one Eloquent query. Load from each and combine in PHP, or create a view in SQL Server. The choice between Eloquent, the query builder and raw SQL is the same as with MySQL; see Laravel: Eloquent vs Query Builder vs Raw SQL.

Calling SQL Server stored procedures

ERP databases are full of stored procedures. Call them with bound parameters:

$rows = DB::connection('erp')->select(
    'EXEC dbo.GetCustomerStatement @CustomerID = ?, @FromDate = ?',
    [$customerId, '2026-01-01']
);

select() returns an array of objects, one per row of the procedure’s first result set.

If you get “The active result for the query contains no fields”, the procedure is returning row counts (from an INSERT or UPDATE) before its SELECT. Add SET NOCOUNT ON; at the top of the procedure. For procedures that only change data, use DB::connection('erp')->statement('EXEC dbo.PostInvoice ?', [$id]);.

Always use ? placeholders. Concatenating request values into an EXEC string is a classic SQL injection hole.

A few SQL Server differences to remember

  • Migrations work on SQL Server, but don’t run them against a database another system owns. Use migrations only for your app’s own tables. Index advice for migrations is in Indexes in Laravel Migrations.
  • Schema names: ERP tables are often in dbo or other schemas; include it in $table ('sales.Orders').
  • Booleans are bit columns (0/1); cast them in the model with protected $casts = ['IsActive' => 'boolean'];.
  • Case sensitivity depends on the database collation, not on Laravel.
  • Slow pages: the debugging steps in How to Find and Fix Slow Queries in Laravel apply, but read the plan with SQL Server’s tools instead of EXPLAIN.

Practice exercises

Exercise 1. php -m shows pdo_sqlsrv, but the browser shows “could not find driver”. What’s the likely cause?

Exercise 2. Write the .env lines for a connection to the named instance SQLEXPRESS on the local machine, database HR, with a trusted self-signed certificate.

Exercise 3. Write a query builder call that returns the 10 most recent rows from dbo.Payments on the erp connection for customer 42.

Answers

Answer 1. The command line and Apache use different php.ini files (or different PHP installs). The extension is loaded in the CLI’s php.ini but not in the one Apache uses. Check Loaded Configuration File in phpinfo(), add the extension= lines there, and restart Apache.

Answer 2.

DB_CONNECTION=sqlsrv
DB_HOST=localhost\SQLEXPRESS
DB_PORT=
DB_DATABASE=HR
DB_USERNAME=laravel_app
DB_PASSWORD=...
DB_ENCRYPT=yes
DB_TRUST_SERVER_CERTIFICATE=true

The SQL Server Browser service must be running so the instance name can be resolved to its port.

Answer 3.

$payments = DB::connection('erp')
    ->table('dbo.Payments')
    ->where('CustomerID', 42)
    ->orderByDesc('PaymentDate')
    ->limit(10)
    ->get();

Laravel turns limit(10) into SELECT TOP 10 on SQL Server.

Summary

  • Laravel talks to SQL Server through pdo_sqlsrv, which needs the Microsoft ODBC Driver (17 or 18).
  • On Windows/XAMPP, use DLLs that match your PHP version and thread-safety build, and check both CLI and Apache.
  • Enable TCP/IP in SQL Server Configuration Manager; named instances need SQL Server Browser and an empty port.
  • For ODBC Driver 18’s certificate error, install a trusted certificate or set trust_server_certificate on internal networks.
  • Use a second connection ($connection = 'erp') to read SQL Server data from a MySQL-based app, and call procedures with bound parameters and SET NOCOUNT ON.

Related articles

Scroll to Top