How to Migrate SQL File in Laravel Migration?
Hello,
In this particular instance, we will be discussing how to execute an SQL file using Laravel migration. This post is intended to provide a straightforward example of running an SQL file through Laravel migration. We will delve into the topic of migrating an SQL file in Laravel. So, without further ado, let's explore the specifics.
If you want to run sql file in laravel migration then we need to use DB::statement(). DB::statement will allow to execute sql file from storage folder in laravel migration.
In this example, i will change viewer column datatype integer to varchar(255). we will create alter.txt file in storage folder to run it.
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.
Defile SQL File
Here, we will create alter.txt file with sql query. so, let's create it.
storage/app/db/alter.txt
ALTER TABLE `posts` CHANGE `viewer` `viewer` VARCHAR(255) NULL DEFAULT NULL;
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;
use Illuminate\Support\Facades\Storage;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
\DB::statement(Storage::get('db/alter.txt'));
}
/**
* 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Migration Remove Default Value Example
- Laravel Migration Change Datatype Timestamp to Datetime Example
- Laravel Migration Change Datatype Date to Timestamp Example
- Laravel Migration Change Datatype Integer to Decimal Example
- Laravel Migration Change Datatype Int to Bigint Example
- Laravel Migration Add Column After Column Example
- Laravel Migration Default Value Current Timestamp Example
- How to Change Column Length using Laravel Migration?
- How to Update Enum Value in Laravel Migration?
- Laravel Migration Add Comment to Column Example
- Laravel Migration Custom Index Name Example
- How to Change Table Name using Laravel Migration?
- How to Remove Column from Table in Laravel Migration?
- Laravel - How to Get Difference of Time in Minutes?