Add new columns to existing table in a migration in Laravel - php

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.

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

Laravel 5.5 Error Base table or view already exists: 1050 Table 'users' already exists

Specifications:
Laravel Version: 5.5.3
PHP Version: 7.1
Database Driver & Version: MariaDB 10.1.26
Description:
C:/Users/user/code/blog/>php artisan migrate
[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists (SQL: create table users (id int unsigned not null aut
o_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 utf8mb4 collate utf8mb4_unicode_ci engine = InnoDB R
OW_FORMAT=DYNAMIC)
[PDOException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists
Steps To Reproduce:
C:/Users/user/code/blog/>laravel new website
C:/Users/user/code/blog/>php artisan make:migration create_lists_table --create=lists
C:/Users/user/code/blog/>php artisan migrate
Problem
It Creates users table and give error but not creating lists table
I Solved My Problem Myself
by Changing My create_users_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::dropIfExists('users');
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Here are the steps I took to solve the same issue:
In the console I wrote php artisan tinker
Then, again in the console, Schema::drop('users')
At the end php artisan migrate and it all worked.
The simple way to solve this problem is run the following command
php artisan migrate:fresh
You can skip migrate the table if table exist in database by add this code:
public function up()
{
if(Schema::hasTable('users')) return; //add this line to your database file
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
Following command solved my problem:
1. php artisan tinker
2. Schema::drop('your_table_name')
3. php artisan migrate
if (!Schema::hasTable('users')) {
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Use !Schema::hasTable('users') ,It will check whether a table already exist in database or not.
If you don't want to drop table then it is a good idea.
Here are the steps I took to solve the same issue:
php artisan make:migration create_tableName_table --create=tableName.
php artisan migrate.
appear error,you can drop all file in migration and all table in database.
create new table as 1.
finish. okay.
Sometime I get the same problem as yours and after I examine it's because sometimes I'm to lazy to type and copy paste the code from create_user_table.php
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
and I forgot to change the table name from this code
Schema::create('users',
To This
Schema::create('what_ever_you_want_to_name_it',
I hope this could help
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.
Step 3:
php artisan migrate
I have different solution, i delete migration table, here my solution
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::dropIfExists('migration');
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
just delete those columns first from database. and run composer update . and then finally run php artisan migrate it would solve your problem. the simplest solution for your problem.
There are two possible solutions for this as mentioned on this link:
https://www.codespeaker.com/laravel-framework/solutions-for-common-errors-on-artisan-commands/
First is rollback
php artisan migrate:rollback
Second is dropping of tables.
Solution:
Go on database -> phpmyadmin if you are on localhost
Delete everything on database that you created
On cmd run php artisan migrate
Agree with Nitesh's answer but I think that's not the best practice to drop the table everytime for no reason. We could also use simple "if" check with condition Schema::hasTable('users') according to the docs. So we can use it as:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
if(!Schema::hasTable('users')
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
This solution will also be feasible in the scenario when you will already have a table and need some modification then you will be able to do anything in the else statement as well.
Migration errors usually occur when using php artisan migrate and your migration has an error.
Within Laravel, there are some ways to reverse something that has been
performed, especially migrations to more robust databases like MySql,
for example.
One way to be reversing the step taken
php artisan migrate
is to run the
php artisan migrate: rollback
It automatically reverses the last migrate performed
You also have the possibility to delegate how many steps will be reversed with the step parameter.
The number says how many steps will be reversed
php artisan migrate: rollback --step=1
Create your migrations by command
php artisan make:migration create_category_table
Then in your database/migrations set your necessary fields and databases,then run this command
pho artisan migrate --pretend
It will show sql statements,copy sql statement of category and paste it in database in sql and just click on run,your migrations would be there,no need to delete users table
Change your Mysql Engine Setting
In config/database.php, change your mysql engine setting to:
'engine' => 'innodb row_format=dynamic'.
Note: This is applicable to Laravel 5.2.14+
you can reset everything by using this command
php artisan migrate:reset
and then you can run this command.
php artisan migrate
remember reset will delete your users table. Please do not use manual approach to delete table or do anything with database. Laravel allows us to do everything by using commands and that's they beauty of it. If you want details about using Laravel migrations then please check this link.
https://laramatic.com/how-to-use-migrations-in-laravel-code-example/
Simple Solutions
Problem:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table Assign_Students already exists.
Here I had a problem with Assign_Students table you may have any
X Y Z Table
ANS: DROP YOUR X Y Z Table from your SQLDB
as I did from my MYSQL I DROP Assign_Students and then I created my New table Example:
php artisan make:model EmployeeSallaryLog -m
Now when you do:
php artisan migrate`
You will find both tables like:
1) Assign_Students
2) EmployeeSallaryLog
For Laravel 8.0, none of the earlier answers worked for me. Then I noticed the line below in the error details when running php artisan migrate:
Loading stored database schema:
/Users/spedley/Sites/monkeys/database/schema/mysql-schema.dump
I deleted the mysql-schema.dump file, ran php artisan migrate again and it worked.
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists (SQL: create table users (id bigint unsigned not null auto_increment primary key, name varchar(191) not null, email varchar(191) not null, email_verified_at timestamp null, password varchar(191) not null, remember_token varchar(100) null, created_at timestamp null, updated_at timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')
The code below works like magic. It runs nicely.
id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
To avoid such error, I think it's better to call Schema::dropIfExists('table-name'); before Schema::create(...) in your migration file. Then try to rollback your migration and migrate again your tables.

I having error migrating my second table in laravel

I am having a problem while running php artisan migrate on my second table after running my first users table in laravel. When I run the second table migration, I get this error:
[PDOException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists
php artisan migrate run all the migrations inside database/migrations folder. So, first you migrated the users table and then you created a new second table migration and ran this command so laravel tried to migrate the users migration again which already exists inside your database and this error is being thrown.
You need to run:
php artisan migrate:refresh
It'll will roll back all of your migrations and then execute the migrate command.
If you are starting off using Laravel Spark or you have used an authentication layer, then the "users" table will give you that error because it already exists. Look through your migrations and you should find a table named as such.
The other possibility is that you have not set up your environment variables correctly and you are using the same database as another project. If that previous project has a "users" table, then this error will also be shown.
Run this php artisan migrate:reset.
Next time when you want to add another table,you need to check first whether the table already exists or not. You can do this by using
if(!Schema::hasTable('users')){
// Write your schema create code here
}
Save the file and than run php artisan migrate command.
I have solved this Problem
Laravel 5.5 Error Base table or view already exists: 1050 Table 'users' already exists
by Changing My create_users_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::dropIfExists('users');
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}

why can not php artisan migrate laravel

when I tried php artisan migrate an error :
{"error":{"type":"Illuminate\\Database\\QueryException","message":"SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'laravel.users' (SQL: drop table `users`)","file":"\/opt\/lampp\/htdocs\/laravel\/coba1\/latihan3\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Connection.php","line":625}}
I use the mysql database, please give solution
You are attempting to drop a table that does not exist. You are either not using the correct database (laravel) or you are doing this as part of a rollback or modification.
Remember that your migrations should include a function that makes changes (up) and a function that undoes those changes (down). Database: Migrations
public function up()
{
Schema::create('users', function (Blueprint $table) {
// columns
});
}
public function down()
{
Schema::drop('users');
}
If you are dropping a table that you are not sure exists you can
Schema::dropIfExists('users');
Check database name (it should be 'laravel' named or change yor config file to right database name) and check existing table users in your database.

How to add column in a table using laravel 5 migration without losing its data?

I have an existing database table and I want to add column on it. However, as I run the php artisan migrate command, it says nothing to migrate. But I already add a Schema for adding table columns. I have read some articles and links that I should run the php artisan migrate:refresh first before the new columns to be added.The problem is, it will erase my existing data in my table. Is there any way I could perform the migration and successfully add columns in my table without deleting my data? Please help me with this. Thanks a lot. Here is my migration code.
public function up()
{
//
Schema::create('purchase_orders', function(Blueprint $table){
$table->increments('id');
$table->string('po_code');
$table->text('purchase_orders');
$table->float('freight_charge');
$table->float('overall_total');
$table->timestamps();
});
Schema::table('purchase_orders', function(Blueprint $table){
$table->string('shipped_via');
$table->string('terms');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::drop('purchase_orders');
}
I want to add column shipped_via and terms in my purchase_orders table.
Use below command to modify the existing table
php artisan make:migration add_shipped_via_and_terms_colums_to_purchase_orders_table --table=purchase_orders
use --create for creating the new table and --table for modifying the existing table.
Now a new migration file will be created. Inside the up() function in this file add these line
Schema::table('purchase_orders', function(Blueprint $table){
$table->string('shipped_via');
$table->string('terms');
});
And then run php artisan migrate
Laravel has a table in your database where it keeps track of all the migrations that are already executed. So by only changing the migration file Laravel will not automatically rerun that migration for you. Cause the migration is already executed by Laravel.
So the best thing to do is to just create a new migration and put the piece of code in it you already have (you were on the right track!).
public function up()
{
//
Schema::table('purchase_orders', function(Blueprint $table){
$table->string('shipped_via');
$table->string('terms');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
You don't need to populate the down function case the table will be dropped by your current purchase_orders migration.
To migrate the new migration just run:
php artisan migrate

Categories