I need to add a new column in my laravel Project, no problem for this, I used the Schema::table()
to update and it's ok. Now I need to find out how many records I have on this table and update with some value.
I have the table Warrants
:
Schema::create('warrant_grants', function(Blueprint $table) { $table->increments('id'); $table->integer('warrant_plan_id'); $table->integer('shareholder_id'); });
So I created the new field with a new migration file:
Schema::table('warrant_grants',function ($table) { $table->string('name',100); });
Now I need to update this field name
in the table with some values, for example if the table has 100 records, then I need to insert in every row the value "Warrant-X" where X is a number starting with 1 to 100. For example:
Warrant-1, Warrant-2, ....Warrant-100.
I spent hours looking for some way to do this using Seeds but I didn't found. So basically i have two questions:
The Laravel migrations will use the Schema facade to create and modify database tables and columns: Schema::create('tasks', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); }); Inside the facade, you could specify the different columns that you want to add.
Show activity on this post. This way a new migration file will be created. Set your column details there, run the migrations using php artisan migrate and that's all. You'll have this new column in your users table without losing previously stored data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With