Refresh table and add data to Laravel 5 Migration

I need to add a new column in my laravel project, no problem for this, I used Schema::table() to update, and that is fine. Now I need to find out how many records I have in this table and update with some value.

I have a Warrants table:

 Schema::create('warrant_grants', function(Blueprint $table) { $table->increments('id'); $table->integer('warrant_plan_id'); $table->integer('shareholder_id'); }); 

So, I created a new field with a new migration file:

 Schema::table('warrant_grants',function ($table){ $table->string('name',100); }); 

Now I need to update this name field in the table with some values, for example, if the table contains 100 entries, then I need to insert the value "Warrant-X" in each row, where X is a number starting from 1 to 100. For example:

Order-1, Order-2, .... Order-100.

I spent hours looking for a way to do this using Seeds, but I did not find. So basically I have two questions:

  • Can I use seeds in Laravel 5 to update values ​​or can I just insert them?
  • Can I create some SQL inside the seeds (or migrations) to make this update for me?
+7
php postgresql laravel
source share
3 answers

Yes, you can do updates / inserts / everything 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++; } 
+6
source share

Based on this link, I found the answer: fooobar.com/questions/547072 / ...

 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.

+4
source share

Other answers are correct. But keep in mind that if you have many records, updating all of them with ORM may take some time. Use raw SQL queries to make this 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 accurate, and you have to make it for your own DB, but you get the point.

+3
source share

All Articles