Laravel Migrations change/update - laravel

How do I properly change / update my migration, I am using Laravel 5.1.
The Docs said that I should use change to update the column e.g.:
$table->string('color', 10)->change();
But where do I have to put it in the migration and what command do I have to use to update just a simply php artisan migrate?
I tried this so far:
public function up()
{
Schema::create('products', function (Blueprint $table)) {
$table->string('color', 5);
});
Schema::table('products', function (Blueprint $table)) {
$table->string('color', 10)->change();
});
}
And used this command:
php artisan migrate
But it did not change.

First, create new migration to change existing table column(s).
php artisan make:migration update_products_table
Then you should do this inside up() method in your new migration:
Schema::table('products', function (Blueprint $table) {
$table->string('color', 10)->change();
});
So, you'll have two migrations. First did already create products table with wrong length of the color string.
Second migration will change color string length from 5 to 10.
After you created seconds migration, run php artisan migrate again and changes will apply to a table.

You might use php artisan migrate:refresh to recreate the table (after editing the original migration).
Beware, it deletes your tables ! Useful for a quick fix on a new install though

Just thought I'd sum up what I did to achieve this, to elaborate on the answer above.
php artisan make:migration change_yourcolumn_to_float_in_yourtable
Then, inside of that migration, in the up() method, I added something like the following:
Schema::table('yourtable', function (Blueprint $table) {
$table->float('yourcolumn')->change(); // Changing from int to float, ie.
});
Then you may need to add a package, to make database modifications like this:
Enter into the console: composer require doctrine/dbal
Then you can go ahead and php artisan migrate to commit the change.

Related

Stripe cashier, ignore customers migration

I installed Laravel Cashier, I migrated the tables but when I want to re-migrate after the first one with a fesh --seed it tells me that there is a problem with the customers table of cashier.
I published the vendors but I find myself with the customers & users table, I deleted the customers table but it still keeps it for me, so I ignored the migrations and kept the 2 subscription tables of cashier but it still doesn't work:
Cannot declare class CreateSubscriptionsTable, because the name is already in use
at database/migrations/2021_07_04_000002_create_subscriptions_table.php:7
Cannot declare class CreateSubscriptionsTable, because the name is already in use
I added this in AppServiceProvider :
Cashier::ignoreMigrations();
Here is my user table, I added the fields of the customers table:
Schema::create('users', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('rank_id')->constrained('ranks');
$table->string('stripe_id')->nullable();
$table->string('pm_type')->nullable();
$table->string('pm_last_four', 4)->nullable();
$table->timestamp('trial_ends_at')->nullable();
$table->string('username');
$table->string('email');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->integer('profile_visibility')->default(\App\Models\User::PROFILE_PUBLIC);
$table->integer('status')->default(0);
$table->timestamp('last_seen_feed')->default(Carbon::now()->toDateTimeString());
$table->timestamp('last_seen_comments')->default(Carbon::now()->toDateTimeString());
$table->rememberToken();
$table->timestamps();
});
php artisan migrate:fresh might be the solution here, try add seeders from different command php artisan db:seed --class:NameofSeedSeeder
More under documentation: https://laravel.com/docs/8.x/migrations

Laravel - How to modify column with migration?

I added foreign key to my table, but forgot to make it nullable().
How can I change column now? As I understand I have to create new migration file with --table flag and add something like: ->nullable()->change();
Correct?
Yes, you need to create another migration or you rollback your previous migration.
There is an example on the Laravel page for modifying columns:
Schema::table('users', function (Blueprint $table) {
$table->string('name', 50)->nullable()->change();
});
See also this link
https://laravel.com/docs/5.8/migrations#modifying-columns
If you prefer a rollback see this link.
https://laravel.com/docs/5.8/migrations#rolling-back-migrations

Doubts over creating and running Laravel migrations

I've been reading the documentation, but I still have some doubts about creating migrations. On my project, I ran the migrate command to create Laravel's default tables (users, password_resets and migrations). Now I want to, one by one, create the migrations for the remaining tables I have planned on my EER diagram. My doubts are the following:
I can use the php artisan make:migration create_new_table to create a new migration and the --create=tablename complement is used to create a new table.
Will --create=tablename immediately create an empty the table on the DB?
Since I already have three tables, should I use --create=tablename for every new one?
After writing all the code, the migrate command will run all my migrations. Do I use this command after I've written migrations for all tables? Will running it again overwrite tables I already have on the DB?
It's probably basic stuff, but I want to be sure before going forward.
Will --create=tablename immediately create an empty the table on the DB?
No, table will be created when you run php artisan migrate. It will create a new migration with "boilerplate" for tablename. In this case, this will be added to the migration file:
Schema::create('tablename', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
Since I already have three tables, should I use --create=tablename for every new one?
It's really just a helper method for the boilerplate. So if you're creating a new one, it will make it easier.
Personally, I prefer creating migrations with php artisan make:model -m SomeModel, which will create the model and a boilerplate migration (because of -m option).
For example, if you run php artisan make:model SomeModel -m, it will a) create a model named SomeModel b) create a boilerplate migration (called somethinig like timestamp_create_some_models_table) with:
Schema::create('some_models', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
I like it because it's easy to stick to Laravels conventions this way (tables in plural, models in singular).
You can also add a namespace to the Model with the command. For example if you have your models in app/Models directory, you'd write php artisan make:model -m Models/SomeModel instead.
After writing all the code, the migrate command will run all my migrations. Do I use this command after I've written migrations for all tables? Will running it again overwrite tables I already have on the DB?
Laravel creates an SQL table specifically for logging which migrations have already run. It will not run the same migration twice, no matter how many times you execute php artisan migrate. Unless you roll them back with some command.
If a table already exists, it will just throw an SQL error saying, can't create a table, since it already exists.
there's no need to supply the table name, so this question is moot
No, you do not need to do this, see 1
migrate saves the name of each migration file in the migrations table and assigns it a batch id. Each subsequent migrate command will check for the existence of all file names in the table, and if they aren't present, will add it to the current batch before running the migrations defined within said file

How to create a column in laravel database without losing data

Suppose I have a table named "foo" with data and also contains foreign key. Now I want to create a column named "description" in this table. Without reset or rollback how to migrate this table?? Because If I reset or rollback the table then all data will be lost.
As per the docs, you just need to create a separate migration to create the new column.
Create the migration
php artisan make:migration add_description_to_foo
Then just set the migration up with the details you want to add, e.g:
Schema::table('foo', function ($table) {
$table->text('description');
});
Then you can just migrate it:
php artisan migrate
This will allow you to add a column without resetting or rolling back your tables, and thus prevent you from losing your data.
Let's start with your schema. Your table name is foo. You want to add a description column to your foo table without losing existing data. You need to create a new migration for this change.
php artisan make:migration add_columns_to_foo_table --table=foo
A new migration file will be created in your migrations directory. Open it and change it like this:
Schema::table('foo', function ($table) {
$table->text('description');
});
Save it and then run
php artisan migrate
description column will be created immediately without losing your old data as last column. In case you want to reposition your description column you need to use after (in case of MySQL) like this:
Schema::table('foo', function ($table) {
$table->text('description')->after('another_column');
});
Hope you got it.
You will find more details here: https://laravel.com/docs/5.3/migrations#creating-columns

In weird state with foreign key after migrations bug

I'm working on my first project using laravel 5. All my migration scripts create tables except for one that adds a foreign key constraint afterward (so both tables are in place before it runs). I found a bug in one of my migration scripts (missing parens made field non-nullable instead of nullable), so after fixing that, I tried doing php artisan migrate:refresh
I hit several errors, so I (mistakenly) decided to get to a fresh state by dropping the tables (using PostgreSQL Studio, via Heroku), but now I'm stuck in a weird state:
When I try php artisan migrate or php artisan migrate --force, it says "Nothing to migrate".
but when I try to rollback or reset or refresh, I get an error:
Undefined table: relation 'users' does not exist (SQL:alter table "users" drop constraint person_id)
That error is from that one migration script that adds the foreign key- I got the overall syntax from here- (http://laravel.com/docs/5.0/schema#foreign-keys)- scream out if wrong:
class AddConstraintToUsers extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->foreign('person_id')
->references('id')
->on('people');
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropForeign('person_id');
});
}
}
More info: based on comment below I deleted the rows from the migrations table so they won't be listed as having already run (in hopes of helping the "Nothing to migrate"). After doing that and trying php artisan migrate I get the same 'relation "users" does not exist" error mentioned above, and now the migrations table shows a 'batch' value of 1 for create_users_table, and 2 for all the others.
Even crazier: since artisan runs migrations in order and thought it had nothing to run (but had been blocked from creating the users table), I created a new migration script to execute last, where the contents were creating that users table. At least it stopped telling me 'Nothing to migrate', BUT it gives a 'duplicate table' error for the OTHER table (called 'updates'), not the one I've actually tried to create twice :p
How can I get back to a normal place-(where either artisan finds my migration scripts to run fresh, or stops trying to rollback the change for the table that's no longer there)- I promise I've learned my lesson to not drop tables. Unfortunately it looks like this problem is less-google-able than usual (or I'm not using the right terms)- any help is greatly appreciated!!
In the end, the way out was to delete the migrations table too (not sure why deleting all the rows in it hadn't been sufficient, but at least I'm back in business now):
I dropped all the tables in my database, including the migrations table
I recreated the migrations table with artisan like so: php artisan migrate:install
Then migrations ran successfully, no problem: php artisan:migrate
Everything working again- hooray!

Resources