Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1 seeding a new column

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');
        });
    }
}
like image 673
V4n1ll4 Avatar asked Sep 27 '22 19:09

V4n1ll4


2 Answers

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'
         ]);
     }
 }
like image 140
Iamzozo Avatar answered Oct 16 '22 19:10

Iamzozo


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();
}
like image 44
Elie Faës Avatar answered Oct 16 '22 21:10

Elie Faës