Saturday, 28 January 2023

Configure Laravel With SQL Server

Integrating Laravel with Microsoft SQL Server allows developers to build powerful web applications while using a robust relational database system. Although Laravel uses MySQL as the default database, it also supports SQL Server through the sqlsrv driver. With the correct configuration and drivers installed, connecting Laravel to SQL Server becomes straightforward.
In this guide, we will walk through the requirements, installation process, configuration steps, and connection testing so you can easily configure Laravel with SQL Server.

How do I connect Laravel 7 to Microsoft SQL Server?

Integrating Laravel 7 with Microsoft SQL Server is a powerful way to build enterprise-level web applications. Laravel is one of the most popular PHP frameworks, while Microsoft SQL Server is known for its reliability, scalability, and advanced database management features. When both technologies are combined, developers can create secure, high-performance applications capable of handling large datasets and complex queries.

Many organizations already use Microsoft SQL Server for their databases. Connecting it with Laravel allows developers to continue using their existing infrastructure while benefiting from Laravel’s modern development features such as migrations, Eloquent ORM, and database query builder.
In this guide, we will walk through the complete process of connecting Laravel 7 with Microsoft SQL Server, including driver installation, project configuration, and testing the connection. By following these steps, you can ensure your Laravel application communicates seamlessly with SQL Server.

Prerequisites

Before starting the integration process, make sure your system meets the following requirements.
First, you must have Laravel 7 installed on your development environment. If Laravel is not installed yet, you can install it using Composer.

Second, you need access to a Microsoft SQL Server instance, either running locally or on a remote server. Ensure that your SQL Server credentials such as hostname, database name, username, and password are available.

Third, the PHP version installed on your system must be compatible with SQL Server drivers. Using an unsupported PHP version may cause driver installation errors.
Finally, ensure that your system has the correct database drivers installed so Laravel can communicate with SQL Server using PDO.

Once these requirements are fulfilled, you can proceed with the configuration steps.

Step 1: Install the Required SQL Server Drivers

To connect Laravel with Microsoft SQL Server, you must install the appropriate PHP drivers. Laravel communicates with databases through PDO (PHP Data Objects), so installing the SQL Server PDO driver is essential.


Windows Installation

If you are using Windows, you need to install the SQLSRV extension for PHP.

Follow these steps:

  • Download the SQL Server PHP drivers from Microsoft's official driver repository.
  • Extract the downloaded files.
  • Locate the correct driver version that matches your PHP version and system architecture (32-bit or 64-bit).
  • Copy the required DLL files into your PHP ext directory.
  • Open your php.ini file and enable the extensions.

Example configuration for a 64-bit system:
extension=php_sqlsrv_74_ts_x64.dll
extension=php_pdo_sqlsrv_74_ts_x64.dll

Example configuration for a 32-bit system:
extension=php_sqlsrv_74_ts_x86.dll
extension=php_pdo_sqlsrv_74_ts_x86.dll


After editing the php.ini file, restart your Apache or PHP server to apply the changes.

Linux Installation

If you are working on Linux, the installation process is slightly different.

You will need to install:
  • FreeTDS
  • pdo_sqlsrv extension
  • SQL Server ODBC drivers

These components allow PHP and Laravel to communicate with Microsoft SQL Server through PDO.


Step 2: Configure Laravel Database Settings

Once the drivers are installed successfully, the next step is to configure your Laravel project so it can connect to the SQL Server database.

Laravel uses environment variables stored in the .env file to manage configuration settings. This approach allows developers to change database credentials without modifying the application code.
Update the .env File

Open the .env file located in the root directory of your Laravel project and add the following database configuration:

DB_CONNECTION=sqlsrv
DB_HOST=server_host
DB_PORT=server_port
DB_DATABASE=databasename
DB_USERNAME=databaseusername
DB_PASSWORD=databasepassword

Replace these values with your actual SQL Server credentials.


For example:

DB_CONNECTION=sqlsrv
DB_HOST=127.0.0.1
DB_PORT=1433
DB_DATABASE=laravel_db
DB_USERNAME=sa
DB_PASSWORD=yourpassword

Configure config/database.php

Next, open the config/database.php file in your Laravel project.

Inside the connections array, you will find the configuration for different database systems. Locate the sqlsrv section and ensure the settings correspond with the values you defined in the .env file.

Example configuration:

'sqlsrv' => [
    'driver' => 'sqlsrv',
    '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' => '',
],

Step 3: Test the Database Connection

After completing the configuration, it is important to verify that Laravel can successfully connect to the SQL Server database.

A simple way to test the connection is by running Laravel migrations.

Run the following command in your project directory:

php artisan migrate

If the command executes successfully and creates tables in your SQL Server database, it means the connection has been established correctly.

Laravel will now be able to perform database operations such as inserting records, retrieving data, updating rows, and running queries.

Verify Installed Extensions

To ensure that the SQL Server extensions are correctly installed, you can check your PHP configuration using phpinfo().

Create a simple PHP file with the following code:

<?php phpinfo(); ?>

Open this file in your browser and search for:
sqlsrv
pdo_sqlsrv

If both extensions appear in the PHP information page, it means the drivers are installed correctly.




Conclusion

Integrating Laravel 7 with Microsoft SQL Server allows developers to build powerful web applications using the flexibility of Laravel and the reliability of SQL Server. With the correct drivers installed and proper configuration in place, Laravel can communicate with SQL Server efficiently.

The integration process mainly involves installing SQL Server drivers, configuring database settings in the .env file, and verifying the connection using Laravel migrations.

Once the setup is complete, developers can fully utilize Laravel’s features such as Eloquent ORM, database migrations, and query builder while working with Microsoft SQL Server.

By following the steps in this guide, you can easily establish a stable and secure connection between Laravel 7 and Microsoft SQL Server, enabling your application to manage data efficiently and scale as your project grows.

Laravel Rest API Localization

Localization is an important feature in modern web applications, especially when your users belong to different regions and speak different languages. When developing APIs with Laravel, it is often necessary to return responses in multiple languages depending on the user’s preference. Laravel provides a powerful localization system that makes it easy to translate application content.

One of the best ways to implement REST API localization in Laravel is by using middleware. Middleware allows you to intercept incoming API requests, check for language preferences, and dynamically set the application language before the request reaches the controller.

In this guide, we will learn how to implement Laravel API localization using middleware, allowing API responses to be translated into multiple international languages.

Why API Localization is Important

API localization helps applications serve users from different countries more effectively. When your API returns responses in the user’s preferred language, it improves usability and enhances the overall user experience.

For example, an application serving users in the United States, France, and Pakistan may need to return responses in English, French, and Urdu. By implementing localization at the API level, you can ensure all messages, validation errors, and responses are translated automatically.

Laravel makes this process simple with its built-in language files and localization helpers.

Step 1: Creating Language Middleware

The first step in implementing localization for Laravel APIs is creating a custom middleware that will detect the language from the API request.

In this example, we will create a middleware called ApiLocalization.

Run the following Artisan command in your Laravel project:

php artisan make:middleware ApiLocalization

After running the command, Laravel will generate a new middleware file in the following directory:

app/Http/Middleware/ApiLocalization.php

This middleware will be responsible for reading the language preference from the request header and setting the application locale accordingly.

Step 2: Update the ApiLocalization Middleware

Next, open the newly created middleware file and update the logic so it checks for a custom request header named X-localization.

This header will allow API clients to specify the language they want in the response.

Example :

public function handle($request, Closure $next)

{

    $local = ($request->hasHeader('X-localization')) 

                ? $request->header('X-localization') 

                : 'en';

    app()->setLocale($local);

    return $next($request);

}

How This Code Works

The middleware performs three simple tasks:

  1. It checks whether the API request contains the X-localization header.
  2. If the header exists, it retrieves the language code from the request.
  3. If the header does not exist, it defaults to English (en).

After determining the language, the middleware sets the application locale using:

app()->setLocale($local);

This ensures that Laravel uses the selected language when returning translated messages.

Step 3: Register the Middleware

Once the middleware is created and configured, the next step is to register it so that Laravel can use it for API requests.

Open the following file:

app/Http/Kernel.php

Inside the $routeMiddleware array, add the new middleware:

'api.localization' => \App\Http\Middleware\ApiLocalization::class,

Now the middleware is available for use in routes.

Step 4: Apply Middleware to API Routes

After registering the middleware, you need to apply it to your API routes.

Open the routes/api.php file and wrap your routes with the localization middleware.

Example:

Route::middleware(['api.localization'])->group(function () {

    Route::get('/message', function () {

        return response()->json([

            'message' => __('messages.welcome')

        ]);

    });

});

Now every request to this route will first pass through the ApiLocalization middleware, which sets the language before the response is generated.

Step 5: Create Language Files

Laravel uses language files to store translations. These files are located inside the resources/lang directory.

Create language folders like:

resources/lang/en/messages.php

resources/lang/fr/messages.php

resources/lang/ur/messages.php

Example English translation:

return [

    'welcome' => 'Welcome to our API'

];

Example French translation:

return [

    'welcome' => 'Bienvenue dans notre API'

];

Example Urdu translation:

return [

    'welcome' => 'ہماری API میں خوش آمدید'

];

Now Laravel will automatically return the translated message based on the selected locale.





Conclusion

Implementing REST API localization in Laravel using middleware is a simple and effective approach for supporting multiple languages. By creating a custom middleware, checking for a language header, and setting the application locale dynamically, you can easily translate all API responses.

Laravel’s powerful localization system combined with middleware allows developers to build globally accessible APIs that adapt to users from different countries and language backgrounds.

By following the steps outlined in this guide—creating middleware, registering it, applying it to routes, and adding translation files—you can quickly enable multi-language API responses in Laravel applications.

This approach ensures your Laravel APIs remain scalable, maintainable, and user-friendly for a global audience.

Laravel DomPDF Package – Generate PDF in Laravel

Understanding the Package The Laravel DomPDF package is one of the most popular tools used by developers to generate PDF files directly from...