Update table and add data in a Laravel 5 Migration Update table and add data in a Laravel 5 Migration laravel laravel

Update table and add data in a Laravel 5 Migration


Based on this link i found the answer: https://stackoverflow.com/a/23506744/4650792

Schema::table('warrant_grants',function ($table){        $table->string('name',100)->after('id')->nullable();    });    $results = DB::table('warrant_grants')->select('id','name')->get();    $i = 1;    foreach ($results as $result){        DB::table('warrant_grants')            ->where('id',$result->id)            ->update([                "name" => "Warrant-".$i        ]);        $i++;    }

Thanks for the help anyway guys.


Other answers are correct. But note that if you have a lot of records, updating all of them with ORM can take time. Use raw SQL queries to do that faster.

Schema::table('warrant_grants',function ($table){        $table->string('name',100)->after('id')->nullable();    });DB::raw("UPDATE warrant_grants SET name=name+id");

The SQL query is not exact, and you have to make it for your own DB, but you get the point.


Yes, you can perform updates/inserts/whatever in your migrations. For example:

Schema::table('warrant_grants', function($table) {    $table->string('name', 100);});$i = 1;foreach (WarrantGrants::all() as $warrant_grant) {    $warrant_grant->update([      'name' => 'Warrant-' . $i    ]);    $i++;}