Hi Developers,
Lets see How To Add New Columns In My Existing Table Laravel . Developers will face this when the client asked to add new column in already deployed project. It is also necessary while upgrading the project. If we create new migration my removing or deleting the already present migration and create and run new migration the sometime it will threw an error if we use any primary key or foriegn key in the migration. To avoid this it is advised to add new column in the existing migration rather than creating new migration .
You have to create a table using this command:
php artisan make:migration create_users_table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Now you want to add new columns in your existing users table
ie, now we are going to add phone_number column in the existing users table
php artisan make:migration add_phone_number_to_users_table --table=users
use the Schema::table() method (as you're accessing an existing table, not creating a new one).
ie;
Schema::table() - > accessing existing table.
Schema::create() - > creating new table
And you can add a column like this:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('phonenumber')->after('name'); // use this for field after specific column.
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('phonenumber');
});
}
After, you can run your migrations
Your new columns(phonenumber) are now added to your existing users table, which you can view in your database.
php artisan migrate
We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.
Be the first to know about releases and tutorial news and solutions.
We care about your data in our privacy policy.
ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.
Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides