Laravel run a database table update query throw migration

how to run update query in laravel migration. update database table content by sql query. raw sql query in laravel 7, laravel 8, laravel 9 migration. How to update a column all rows by laravel migration


Create a update query in laravel migration

If you don't access to your project database and want to change a column value according to the condition then create a migration. Like In products table have a status column which has two values active and inactive but now we replace status column values "active"=> 1 and "inactive"=>0 see below example.

Run this command for create new migration

php artisan make:migration change_status_products_table

This command create a migration see in below example and we run a query for update status values by 0 and 1.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use App\Models\Product;

class ChangeStatusProductsTable extends Migration
{

  public function up()
  {
    Product::where(["status", "Active"])->update(["status" => '1']);
    Product::where(["status", "Inactive"])->update(["status" => '0']);
  }

  // rollback the migration
  public function down()
  {
    Product::where(["status" => '1'])->update(["status", "Active"]);
    Product::where(["status" => '0'])->update(["status", "Inactive"]);
  }
}

php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Random tutorial links