How to add column to existing table in laravel? - php

I'm new to laravel framework. For making a blog URL's to SEO friendly, I need to add an extra column to the existing blog tables for the laravel website. Can we directly add a column to a table directly in the database or not? Can we add a column without commands or migrations? Would you please suggest an easy method to add the column?

Add migration
php artisan make:migration add_fieldname_to_tablename
Code methods migration
public function up()
{
Schema::table('tablename', function (Blueprint $table) {
$table->datatype('column_name')->nullable();
});
}
public function down()
{
Schema::table('tablename', function (Blueprint $table) {
$table->dropColumn('column_name');
});
}
Run migration
php artisan migrate

Better is to add at migration level but if you want to directly add at DB level that is also an option. But update migration as well so that it will have all the columns.

Related

laravel, update table structure but get error table already exist when use php artisan migrate

I have table and I wanted to update on some columns, or if I wanted to add new column the problem is when I want to use php artisan migrate command gives me error table already exist, also Im using depoly file and the command inside it is php artisan migrate --force so hope this is correct or have to add any more command??
public function up()
{
Schema::create('payment_methods', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->string('paymentreference')->unique();
$table->string('payment_token');
$table->string('cardnumber'); //updated
$table->string('cardbin')->nullable();
$table->string('cardlast4');
$table->string('cardtype');
$table->string('expirymonth');
$table->string('expiryyear');
$table->string('cardholdername'); //added
$table->timestamps();
});
}
To added new or update field like profile in payment_methods.
Try
Run command:
php artisan make:migration add_profile_to_payment_methods
And in the up() method of the new migration file generated, use Schema::table() method to add the new columns or modifying the table.
public function up()
{
Schema::table('payment_methods', function (Blueprint $table) {
$table->string('profile')->nullable();
});
}
public function down()
{
Schema::table('payment_methods', function (Blueprint $table) {
$table->dropColumn('profile');
});
}
}
Then run migration to update the table using php artisan migrate
You need a new migration to modify existing table.
Create new migration:
php artisan make:migration modify_payment_methods_table
Then open the migration file and put following code in there:
public function up()
{
Schema::table('payment_methods', function (Blueprint $table) {
$table->string('cardnumber')->change();
$table->string('cardholdername');
});
}
public function down()
{
Schema::table('payment_methods', function (Blueprint $table) {
$table->integer('cardnumber')->change(); // todo: if this was not an integer then fix this to be correct type instead of integer to avoid issue in case if you will have to rollback the migration
$table->dropColumn('cardholdername');
});
}
After this run
php artisan migrate
To do this successfully you may need to install additional dependency doctrine/dbal.
You can install that easily with composer:
composer require doctrine/dbal
You have manipulated or an error has occurred in any of the migrations.
Well, now in the migrations table, there isn't a row that contains create_payment_methods_table in the migrations column.
As it does not exist, but the table to which the migration refers, if it exists in your database, it fails you, since the process is as follows:
When you refresh, Laravel reads the migrations table, and executes
each migration file in order, first executing the down or deletion of
the table.
After executing that step in all migrations, go through the UP. When
the down of that table does not exist, when arriving at its demo
file, the up finds that it already exists. And that's why it fails
you.,
The solution is to delete manually the referenced table and rerun the migration

Add new columns to existing table in a migration in Laravel

I want to add some new columns in my existing table users in laravel.
I have already googling for that and following those search I have already created migration using the command php artisan make:migration add_columns_to_users.
add_columns_to_users.php
public function up()
{
Schema::table('users', function($table) {
$table->string('address');
$table->string('city');
$table->string('tribe');
$table->string('country');
$table->integer('student_id');
$table->string('tribe_university_name');
$table->string('student_program_of_study');
$table->string('faculty');
$table->string('level');
});
}
public function down()
{
Schema::table('users', function($table) {
$table->dropColumn('address');
$table->dropColumn('city');
$table->dropColumn('tribe');
$table->dropColumn('country');
$table->dropColumn('student_id');
$table->dropColumn('tribe_university_name');
$table->dropColumn('faculty');
$table->dropColumn('level');
});
}
After creation, I run this command php artisan migrate.
But got the same error:
Base table or view already exists: 1050 Table 'users' already exists (SQL: create table users (id int unsigned not null auto_increment primary key, name varchar(255) not null, email varchar(255) not null, password varchar(255) not null, remember_token varchar(100) null, created_at timestamp null, updated_at timestamp null) default character set utf8 collate utf8_unicode_ci)
Full name of user table 2014_10_12_000000_create_users_table.php and the other name is 2019_04_11_074552_add_column_to_users.php
How to solve this?
My main query is How to add new columns in my existing table?
If you check at the error trace:
Base table or view already exists: 1050 Table 'users' already exists
This means that the users table already exists so when you run your migrations it is trying to create a table that is already created in your database.
Note: Don't forget to backup your database first
Delete users table from the database also delete users entries from migrations table.
After, execute the migrate Artisan command:php artisan migrate
Now another your Question is: How to add new columns in my existing table?
You have to create a table using this command:
php artisan make:migration create_users_table
The output you got it like this: Created Migration: 2019_04_12_070152_create_users_table
Your Migration structure is something this:
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
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). 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: php artisan migrate
Your new columns(phonenumber) are now added to your existing users table, which you can view in your database.
If you have still any doubt, see this video
The problem comes from the php artisan migrate that will try to migrate both files when 2014_10_12_000000_create_users_table.php is already migrated, so IMO two possible solutions here :
Rollback the users table from the DB and rerun the migrate cmd.
Add the migration name inside the migrations table so the cmd will not try to run it for the second time.
Modifying current migration wont work, because it's entry in migration table is already there. So to make any changes in already existing table, you need to create new migration script.
// remember `create` replaced by `table` here
Schema::table('users', function (Blueprint $table) {
// add whichever new columns you want to
});
Follow these steps,
php artisan make:migrate modify_user_table
open modify_user_table file in database/migrations directory
Add new columns as at top I wrote.
Now save the file after adding new columns into new migration file
cmd -> php artisan migrate
EDIT
If there is no user data then Open 2014_10_12_000000_create_users_table.php file and add Schema::dropIfExists('users'); before Schema::create('users'... line.
If there is data then you can take a backup, again follow the above step 1.
You need do little modification in your artisan command
artisan make:migration add_columns_to_users_table
You then need to use the
Schema::table() method (as you're accessing an existing table, not creating a new one). And you can add a column like this
public function up()
{
Schema::table('users', function($table) {
$table->type('column');
});
}
add the rollback option:
public function down()
{
Schema::table('users', function($table) {
$table->dropColumn('column');
});
}
Then you can run your migrations:
php artisan migrate
Please do the step 1.
php artisan migrate:reset
Step 2: Go to your database using PHPmyadmin (or similar) and delete all remaining tables
including the migration table.
After all please do Step 3 php artisan migrate
You probably got the error because you tried to create another Users table, which is already exist on your database. That could be the reason why you find error Base table or view already exists: 1050 Table 'users' already exists.
So, the solution is try to alter you existing Users table, instead to run another syntax to create and override Users table. By create another alter class inside your data migration folder. It used to be inside your modules folder on your Laravel Project (../database/migrations/).
After you find the directory, create new alter class. For example, alter_users_table.php.
So, if you would like to add another column (e.g.: age column, with type int, nullable) on your Users table, you could code like this on alter_users_table.php:
class AlterUsersAddAge extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('Users', function (Blueprint $table) {
$table->int('age')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('Users', function (Blueprint $table) {
$table->dropColumn('age');
});
}
}
After that, try to run php artisan migrate on your terminal.
Now you should see another new column age on your Users table.

laravel - update database

I created an app in Laravel. In the beginning, I made a migration with the following content:
public function up()
{
Schema::create('kundens', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->unsignedInteger('user_id');
$table->string('vorname');
$table->string('nachname');
$table->string('strasse');
$table->integer('plz');
$table->string('wohnort');
$table->string('mail');
$table->integer('telefon');
$table->string('geburtsdatum');
});
}
No I want to add some tables like kaufpreis or "modernisierung". I added them under the other tables but when I save the file and write in the terminal I get the error:
nothing to migrate.
So now how can I add some tables for more information?
You should create a new migration for kaufpreis and modernisierung.
The main migration for kundens did already run (see migrations table).
php artisan migrate:fresh is also an option, if you are developing locally.
Don't do this when you work with other people / production as it will erase the tables and create new ones (data will be lost)

Laravel migrate:rollback adding and deleting table columns

I have used the php artisan migrate:make add_something_to_to_user_table --table=users
and coded
Schema::table('users', function(Blueprint $table)
{
$table->string('description1');
$table->string('description2');
$table->string('description3');
});
and added three fields and gave php artisan migrate and the fields got stored in to the database
also found that the migration table is updated with the row 2014_11_05_145536_add_something_to_to_user_table
now when i use php artisan migrate:rollback
The 2014_11_05_145536_add_something_to_to_user_table row in the migration table is missing but the columns added to the users table remains the same
why it is not deleting the fields in the table also which results in error while using php artisan migrate again...
You should have a down() method in you migration that should look like this:
public function down()
{
Schema::table('users', function($table)
{
$table->dropColumn(array('description1', 'description2', 'description3'));
});
}
That will be called on rollback and will take care of removing the columns added by the migration.
According to laravel 7+ doc this will also work when you need to drop multiple columns at the same time.
public function down(){
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['description1', 'description2', 'description3']);
});
}
Add down public function to drop users table when rollback..
public function down()
{
Schema::drop('users');
}

Laravel Add a new column to existing table in a migration

I can't figure out how to add a new column to my existing database table using the Laravel framework.
I tried to edit the migration file using...
<?php
public function up()
{
Schema::create('users', function ($table) {
$table->integer("paid");
});
}
In terminal, I execute php artisan migrate:install and migrate.
How do I add new columns?
To create a migration, you may use the migrate:make command on the Artisan CLI. Use a specific name to avoid clashing with existing models
for Laravel 5+:
php artisan make:migration add_paid_to_users_table --table=users
for Laravel 3:
php artisan migrate:make add_paid_to_users
You then need to use the Schema::table() method (as you're accessing an existing table, not creating a new one). And you can add a column like this:
public function up()
{
Schema::table('users', function($table) {
$table->integer('paid');
});
}
and don't forget to add the rollback option:
public function down()
{
Schema::table('users', function($table) {
$table->dropColumn('paid');
});
}
Then you can run your migrations:
php artisan migrate
This is all well covered in the documentation for both Laravel 4 / Laravel 5:
Schema Builder
Migrations
And for Laravel 3:
Schema Builder
Migrations
Edit:
use $table->integer('paid')->after('whichever_column'); to add this field after specific column.
I'll add on to mike3875's answer for future readers using Laravel 5.1 and onward.
To make things quicker, you can use the flag "--table" like this:
php artisan make:migration add_paid_to_users --table="users"
This will add the up and down method content automatically:
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
//
});
}
Similarily, you can use the --create["table_name"] option when creating new migrations which will add more boilerplate to your migrations. Small point, but helpful when doing loads of them!
In case you want to add new column as a FOREIGN KEY to an existing table.
Create a new migration by executing this command : make:migration
Example :
php artisan make:migration add_store_id_to_users_table --table=users
In database/migrations folder you have new migration file, something like :
2018_08_08_093431_add_store_id_to_users_table.php (see the comments)
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddStoreIdToUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
// 1. Create new column
// You probably want to make the new column nullable
$table->integer('store_id')->unsigned()->nullable()->after('password');
// 2. Create foreign key constraints
$table->foreign('store_id')->references('id')->on('stores')->onDelete('SET NULL');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
// 1. Drop foreign key constraints
$table->dropForeign(['store_id']);
// 2. Drop the column
$table->dropColumn('store_id');
});
}
}
After that run the command :
php artisan migrate
In case you want to undo the last migration for any reason, run this command :
php artisan migrate:rollback
You can find more information about migrations in the docs
If you're using Laravel 5, the command would be;
php artisan make:migration add_paid_to_users
All of the commands for making things (controllers, models, migrations etc) have been moved under the make: command.
php artisan migrate is still the same though.
In Laravel 8
php artisan make:migration add_columnname_to_tablename_table --table=tablename
then after creating migration in
public function up()
{
Schema::table('users', function (Blueprint $table) {
// 1. Create new column
$table->datatype('column_name')->nullable();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
// 1. Create new column
$table->dropColumn('column_name');
});
}
then run
php artisan migrate
if you face error then rename the migration name with the date before the table created and then run again php artisan migrate
You can add new columns within the initial Schema::create method like this:
Schema::create('users', function($table) {
$table->integer("paied");
$table->string("title");
$table->text("description");
$table->timestamps();
});
If you have already created a table you can add additional columns to that table by creating a new migration and using the Schema::table method:
Schema::table('users', function($table) {
$table->string("title");
$table->text("description");
$table->timestamps();
});
The documentation is fairly thorough about this, and hasn't changed too much from version 3 to version 4.
Laravel 7
Create a migration file using cli command:
php artisan make:migration add_paid_to_users_table --table=users
A file will be created in the migrations folder, open it in an editor.
Add to the function up():
Schema::table('users', function (Blueprint $table) {
// Create new column
// You probably want to make the new column nullable
$table->integer('paid')->nullable()->after('status');
}
Add to the function down(), this will run in case migration fails for some reasons:
$table->dropColumn('paid');
Run migration using cli command:
php artisan migrate
In case you want to add a column to the table to create a foreign key constraint:
In step 3 of the above process, you'll use the following code:
$table->bigInteger('address_id')->unsigned()->nullable()->after('tel_number');
$table->foreign('address_id')->references('id')->on('addresses')->onDelete('SET NULL');
In step 4 of the above process, you'll use the following code:
// 1. Drop foreign key constraints
$table->dropForeign(['address_id']);
// 2. Drop the column
$table->dropColumn('address_id');
this things is worked on laravel 5.1.
first, on your terminal execute this code
php artisan make:migration add_paid_to_users --table=users
after that go to your project directory and expand directory database - migration and edit file add_paid_to_users.php, add this code
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('paid'); //just add this line
});
}
after that go back to your terminal and execute this command
php artisan migrate
hope this help.
First rollback your previous migration
php artisan migrate:rollback
After that, you can modify your existing migration file (add new , rename or delete columns) then Re-Run your migration file
php artisan migrate
WARNING: this is a destructive action. If you use this ensure you back up your database first.
You can simply modify your existing migration file, for example adding a column in your table, and then in your terminal typing :
$ php artisan migrate:refresh
Add column to your migration file and run this command.
php artisan migrate:refresh --path=/database/migrations/your_file_name.php
STEP 1
php artisan make:migration add_sex_to_users_table --table=users
STEP 2
In the newly generated migration file, you will find up and down hook methods. in up hook, add there columns that you want to add, and in down hook, add there columns that you need to remove. for example, Me i need to add sex on column of users, so I will add there following line in the up hook.
$table->integer('quantity')->default(1)->nullable();
So I have something like this
public function up()
{
Schema::table('service_subscriptions', function (Blueprint $table) {
$table->integer('quantity')->default(1)->nullable();
});
}
STEP 3
Run the migration command as follows
php artisan migrate
Then you will have a new column added
In laravel 8
php artisan make:migration add_paid_to_users_table --table=users
public function up()
{
Schema::table('users', function($table) {
$table->integer('paid');
});
}
In laravel 9
add a new column in existing table
php artisan make:migration add_paid_to_users_table
if you want to create new migration then do the below code
php artisan make:migration create_users_table --create=users
First you have to create a migration, you can use the migrate:make command on the laravel artisan CLI.Old laravel version like laravel 4 you may use this command
for Laravel 4:
php artisan migrate:make add_paid_to_users
And for laravel 5 version
for Laravel 5+:
php artisan make:migration add_paid_to_users_table --table=users
Then you need to use the Schema::table() . And you have to add the column:
public function up()
{
Schema::table('users', function($table) {
$table->integer('paid');
});
}
If you don't want to split the blueprint(schema) into two migration file then the best thing you can do is drop the table from the database and then rename the migration file's last number and do
php artisan migrate
This helps you to protect the data of other tables.
Run this command:
php artisan migrate:fresh --seed
it will drop the table and re add it updating all the columns adding to the database
What you can do is Like,
Schema::create('users', function ($table) { $table->integer("paid"); });
After Writing this write command php artisan migrate or php artisan refresh
What i personally prefer is to refresh rather than fresh migration because if you do fresh migrate it will remove all the data refresh will not.
but only exception is if you do refresh and if you have any foreign key in table so it will not going to re-establish the relationship so you will get error like,
Cannot add foreign key constrain
If none of the solve worked, you might have recreated the migration file then added a new column and tried to run php artisan migrate to update the old table which will try to create that table but the table already exists so it gives an error. To solve that rename the migration file as previously named (started with a date), then add new column run php artisan migrate that will actually update the old one instead of create, solved my problem.
Although a migration file is best practice as others have mentioned, in a pinch you can also add a column with tinker.
$ php artisan tinker
Here's an example one-liner for the terminal:
Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ $table->integer('paid'); })
(Here it is formatted for readability)
Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){
$table->integer('paid');
});

Categories