5

I have a database table called locations and I need to add a new status column. I have setup the following migration file which adds the field fine when i run php artisan migrate, but how can I insert a value of Active for each row in the table?

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddStatusToLocationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('locations', function(Blueprint $table)
        {
            $table->string('status')->after('email');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('locations', function(Blueprint $table)
        {
            $table->dropColumn('status');
        });
    }
}
V4n1ll4
  • 5,973
  • 14
  • 53
  • 92

3 Answers3

3

You can set your field to a default value

$table->string('status')->after('email')->default('active')

If you need to update just the current records, you can do with seeding:

run this artisan command:

php artisan make:seeder AddStatusSeeder    

Then in your AddStatusSeeder:

<?php

use Illuminate\Database\Seeder;

class AddStatusSeeder extends Seeder
{
     /**
     * Run the database seeds.
     *
     * @return void
     */
     public function run()
     {
         DB::table('locations')->update([
            'status' => 'Active'
         ]);
     }
 }
Iamzozo
  • 2,341
  • 18
  • 21
  • Thanks for the above. Any ideas about how to modify the above when you want a unique ID? Currently when I generate a UUID the same ID populates each row with the same value. Code: 'public_id' => (string)Uuid::generate(4) – ejntaylor Jun 28 '19 at 07:35
  • `DB::table('your-table')->update([...])` without a `where` condition means, it will update all records. You need to loop through all rows and update the UUID individually. – Iamzozo Jul 01 '19 at 17:09
1

You have two solutions

You can totally add a value to your existing seeder for this table

You also can create a new seeder in which you fetch every location, add your new field value and save it like so

foreach(Location::all() as $location){
    $location->status = 'Active';
    $location->save();
}
Elie Faës
  • 3,215
  • 1
  • 25
  • 41
0

You need to use database seeding. You can either create a model for the locations table or use the DB::table way of inserting.

You can then run php artisan migrate --seed to create the schema and populate the DB.

fire
  • 21,383
  • 17
  • 79
  • 114
  • 1
    Yes I already have a model for locations table and a seeder file. But my question is, how do I seed a new column? – V4n1ll4 Sep 08 '15 at 08:53