Laravel Migration Execute SQL Query Example
Hi Friends,
Here, I will show you laravel migration execute sql. Here you will learn laravel migration run sql file. This post will give you a simple example of how to run sql query in laravel migration. we will help you to give an example of laravel migration run sql query.
If you want to run sql query in laravel migration then we need to use DB::statement(). DB::statement will allow to execute sql query in laravel migration.
In this example, i will change viewer column datatype integer to varchar(255).
So, let's see the simple example of laravel migration change integer to string using DB::statement.
Default Created Table
Here, you will see the default created table screenshot.
Create Migration
Create new migration using following command:
php artisan make:migration change_datatype_column
Now, You can update it as like the bellow:
database/migrations/migration_name.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
\DB::statement('ALTER TABLE `posts` CHANGE `viewer` `viewer` VARCHAR(255) NULL DEFAULT NULL;');
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('posts', function (Blueprint $table) {
});
}
};
Now, you are ready to run migration command:
php artisan migrate
You will see the layout as like the below:
I hope it can help you...