Write SQL queries in Laravel migration.
Sometimes we need to write some manual SQL queries in Laravel migration. eg. I want to add a new field cast_the_vote in existing table users which have age of users. If age is greater than 18 then save true in cast_the_vote otherwise false in migration. So your migration file should looks like:-
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ChangeUsersTable extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->boolean('cast_the_vote')->default(false);
});
$this->upadateDB();
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('cast_the_vote');
});
}
private function upadateDB()
{
DB::statement('UPDATE users
SET cast_the_vote = true
where age > 18');
}
}
When you run php arisan migrate then it will automatically run the DB Query as will.
Comments
Post a Comment