Laravel 5.2 how to update migration without losing data - php

I'm using laravel 5.2 and I usually update my database according to project requirements, so I'd like to do it without losing database records.
I don't mean how to seed my database.. I mean when my database is live and I want to update it throw laravel migration.
I was going throw Laravel Documentation but I found nothing, so I hope to find somebody help me

Since you already have data in your tables then instead of rolling back your migrations (which will cause existing data losses) you can create new migration files to update your tables. Suppose you have a table users with columns name, email, password. You stored data in that table. Then you realized that you also do need to add a new column named mobile_no to your users table. To do this you need to create a new migration file. Command will be:
php artisan make:migration add_mobile_no_columns_to_users_table --table=users
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.

Please note that when you add a new column for a table while already there are data, you have to set a default value for new column or make it nullable type.. otherwise you will endup with error

Make sure that when you are adding new column in your table, that column should be nullable, and should not be unique. Otherwise you will face error. Because when a new column is created it will be empty(not unique). In that condition you have to rollback the migration.

Make a new migration with
php artisan make:migration change_body_to_nullable_in_reviews_table --table=reviews
where you put this
public function up()
{
Schema::table('reviews', function (Blueprint $table) {
$table->text('body')->nullable()->change();
});
}
public function down()
{
Schema::table('reviews', function (Blueprint $table) {
$table->text('body')->nullable(false)->change();
});
}
And then run PHP artisan migrate

Related

Laravel bug: making column nullable stops it from being added to table

I have a SQLite database with the following migration defined:
Schema::create("views", function(Blueprint $table){
$table->integer("match_id");
$table->string("pov");
$table->string("teams");
$table->text("moves");
$table->bigIncrements("id");
$table->date("created_at");
$table->date("updated_at");
});
Note: id is the primary key of the table, match_id should just be treated as any other column.
This all works just fine, but I want match_id to be nullable. I tried changing the $table -> integer("match_id") to the following:
$table->integer("match_id")->nullable()->change();
//Also tried $table->integer("match_id")->nullable(true)->change();
I also ran 'composer require doctrine/dbal', which I saw online
When I try running php artisan migrate, it says there is nothing to migrate. And when I run php artisan migrate:fresh, for some reason the match_id column just doesn't get added to the database at all, even though every other column works just fine. Any reason this might be?
Since migrate:fresh is an option (as pointed by #xenooooo), just edit your original migration to:
Schema::create("views", function(Blueprint $table) {
$table->bigIncrements("id");
$table->integer("match_id")->nullable();
$table->string("pov");
$table->string("teams");
$table->text("moves");
$table->timestamps();
});
This should fix the problem. With migrate:fresh you don't need a second migration just to change, since it will drop all tables and create everything again. Also I've changed the order of the primary key (just in case of this be the problem of migrate:fresh not creating the match_id column), and changed the timestamps format. In Laravel you don't need to create manually the timestamps, "$table->timestamps()" do it for you :)
By using this
$table->foreignId('match_id')->nullable();
$table->integer('match_id')->nullable();
In Laravel 7
you can make "match_id" (nullable & integer) or foreign-key by using this code
$table->foreignId('test_id')->nullable();
$table->integer('tint_id')->nullable();
As i used it in picture
here is code
and here is my db

I can’t add new columns to the table from laravel even after following the procedure of migration?

I am following all the steps for adding new column votes to the user table from laravel, still there isn't in the database? Please tell me where is my mistake?
Firstly
php artisan make:migration add_votes_to_users_table --table=users
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('votes');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('votes');
});
}
php artisan migrate
enter image description here
Error from cmd-
In Connection.php line 647:
SQLSTATE[42S01]
And
In Connection.php line 449:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already
exists
I am suspecting that the reason you are getting this errors can come from 2 sides.
1) you created users table yourself without run any migration
2) a migration was interrupted.
If the above does not work try:
php artisan migrate:reset
to rollback all your changes or if you want to move back 1 step at a time you can try:
php artisan migrate:rollback --step=1
Last if you are sure you can start over and you are ok with that you can run:
php artisan migrate:fresh
This will drop all the tables (check the database just to be sure as well and drop yourself any remaining even though i don't think anything will be left, never happened to me) and then run
php artisan migrate
all over again
Check your data base. the users table already exit or not. if you create manually. you get this type of error. if users table ther you can remove manually from data base.
Thanks all of you for your suggestions, Sasa Blagojevic you are right about one thing my database was created in wrong way. Actually main problem arise when I created the database first time that time SQLSTATE[42000] appeared for user table. That why when updating the table previous error was still showing. After solving it there wasn't error now.

Run artisan in Laravel code without creating migration records in the table migrations

I have this code in my function to run all migrations files in a folder to create new tables in a new database on the fly. However, every time I run it, it creates a new record in the table migration which is normal. But the next time I run the function again, the migration files are excluded because they have been run before.
How do I force it not to write anything to the table "migrations"? because I don't want this to be a part of the deployment. Those tables are used for creating new tenant client.
Artisan::call('migrate', array('--path' => 'database/templates', '--force' => true));
After understanding your goal better, it sounds like you wish to create additional tables when an event happens.
For this you'll just need to use the Schema builder to do it and avoid using migrations altogether. Consider the following example:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
Schema::create('new_table_name', function (Blueprint $table) {
$table->increments('id');
// additional columns
$table->timestamps();
$table->softDeletes();
});
You can wrap this in a new class method to trigger when you want to create an additional table without effecting migrations.
If you wish to drop a table later you can run:
Schema::dropIfExists('new_table_name');
It looks like I can use the option --pretend to dump all the queries without writing the migration batch
Options:
...
--pretend Dump the SQL queries that would be run.
...

Laravel 5 migration gone wrong

I created a new migration with php artisan make:migration --table=my_table and proceed to create a new column to an existing table. Said column is supposed to be a unique index, but I forgot to make it nullable, for that reason, php artisan migrate failed, as multiple rows would have a duplicate entry (which would be an empty string '')
Up to this point, the logical way to go is to add nullable to the column and re-run migrations. But since the new column already exist on the table (the migration failed when adding the unique key, but the column creation was successful) I have to drop it first.
My first thought was to run php artisan migrate:rollback but it executed a previous migration, not the one I just created.
Up to this point, what is the right way to do this? should I log into database cli and write query manually or laravel provide a way to handle this via php artisan?
I do think you can modify the original migration for your table and add the nullable, but you need to do this on the old migration. As you noticed, a new migration will just apply a patch to an existing table.
After modifying the migration you can rollback and forward again. Of course you need to be careful with your data (in case you need them check Database Seeding.
You can also use php artisan migrate:refresh this will delete all tables and data (so be really careful), but it should recreate your table with the new structure.
Try this:
php artisan migrate:rollback --table=table_name_here

Why does 'php artisan migrate' command create a migration table along with the table i intended to create?

app/migrations/create_user.php
public function up(){
Schema::create('interns', function($intern){
$intern->increments('id');
$intern->string('name');
$intern->integer('salary');
});
}
So the above function creates a table called "intern" but along with that it also creates a "migrations" table on running the command "php artisan migrate". Why is it doing this?
It's Laravel's way of keeping track of which migrations have been run.
Let's assume you make another table but it doesn't work right, so you need to run php artisan migrate:rollback. Laravel will know that the second table was created in the second batch and only rollback that one, leaving your interns table alone.
Every time you run another migration, that table will be updated with the migration's file name and the batch it was ran in.
The migrations table is for laravel to track the version the database is running.
For each migration it'll insert a new row into the migrations table, so that when you run migrate:rollback it knows what migrations to undo, and likewise, it knows what migrations to run going forward.
If you look at the migrations table you'll see it keeps a record of the migration name and batch number. The batch number is a sequential order that the migrations are run in. For example, you might create a users table. You run that and laravel logs the filename and batch number. Next you might add an accounts table that the users table is associated to. For this you would create 2 new migrations, one to create the new accounts table the other to edit the users table to add a new column account_id. Next time you migrate, both of the new migrations will be run, but assigned under the same batch id.

Categories