Laravel migration with SQL Server
Laravel is a popular PHP framework for building web applications. It comes with an elegant syntax for defining database migrations, which makes it easy to manage database schema changes. By default, Laravel supports MySQL, PostgreSQL, and SQLite databases. However, Laravel can also be used with Microsoft SQL Server by installing the SQL Server driver. In this answer, we will discuss how to perform Laravel migrations with SQL Server.
First, you need to install the SQL Server driver for Laravel. You can do this by running the following command in your terminal or command prompt:
composer require microsoft/sqlserver-driver
Once the driver is installed, you need to configure your Laravel application to use SQL Server as the database. Open the .env
file in your Laravel project root directory and set the following variables:
DB_CONNECTION=sqlsrv
DB_HOST=127.0.0.1
DB_PORT=1433
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
Make sure to replace your_database_name
, your_username
, and your_password
with the appropriate values for your SQL Server database.
Now that your Laravel application is configured to use SQL Server, you can create a new migration file by running the following command:
php artisan make:migration create_users_table --create=users
This command will create a new migration file named create_users_table.php
in the database/migrations
directory. Open the file and modify it to use the SQL Server syntax for creating tables:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::connection('sqlsrv')->create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::connection('sqlsrv')->dropIfExists('users');
}
}
Notice that we are using the Schema::connection('sqlsrv')
method to specify that we want to use SQL Server for this migration.
Finally, you can run the migration by running the following command:
php artisan migrate
This command will execute the migration file and create the users
table in your SQL Server database.
In summary, to perform Laravel migrations with SQL Server, you need to install the SQL Server driver, configure your Laravel application to use SQL Server, create a new migration file with the appropriate syntax, and run the migration command.