Doubts over creating and running Laravel migrations - laravel

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

Related

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

Database Migration Laravel 5.2 Arrange Table

I have a create_users_table at the top and with foreign key to roles table but the location of roles table is at the bottom of create_users_table. So what happen is the create_users table can't see the roles table because it's not yet created. See attached image:
Do I need to recreate a users table so that it will come up below to roles table?
Do I need to recreate a users table so that it will come up below to
roles table?
You can't add a foreign key to a table that does not yet exist. If you want to manage your database through migrations, you do need to put them in the right order.
However, you can also add it as a separate migration, so that you have
create users table
create roles table
alter users table to add role_id field and foreign key
That way you don't have to rearrange existing migrations if you e.g. need to make changes to the database mid-project.
if its just a beginning of the project and if you are not using database migrations versioning yet you could just rename the datetime timestamp at migrations filename to rearrange the migrations. something like this would rearrange migrations to the required order. see i changed the year of 2016_08_13_001252_create_roles_table.php to 2014_08_13_001252_create_roles_table.php.
2014_08_13_001252_create_roles_table.php
2014_10_12_000000_create_users_table.php
2014_10_12_100000_create_password_resets_table.php
2016_08_08_005720_create_messages_table.php
migrations run in the datetime order of the filenames. Only the new migrations are run at each run. so, if you bring such changes to the files like renaming the file you need to drop database and create again, then run the migrations.
sometime after doing this you might need to run following commands in the project
composer dump-autoload and/or php artisan clear-compiled.
if you are running the migrations verisoning?
migrations are something related to databases and its not meant for dropping all the tables and recreating each and every time when you need to bring a change. If the database is live or if you have completed major database design you could use versioning. one of the purpose of migrations made in that way (datetime order and only new ones are migrated each time) is that only changes are brought to the old migrations created.

How to migrate schema in Laravel without loss of existing data?

I have table named "user_table" has certain columns and table has filled with data. I want to add some more columns. So how can I migrate that new schema in Laravel without loss of existing data. Even I can not do rollback because when I will do then all stored data will be deleted. So, can somebody please help me to solve this issue ?
You can create new table columns in migrations without loss of data. If you alter a column or drop a column, then of course you will manipulate existing data. As long as you are only adding new columns, then you can run
php artisan make:migration alter_my_table_add_columns
and update your existing schema. Then you can safely run
php artisan migrate
In your new migration you would then add:
Schema::table('my_table', function ($table) {
$table->string('my_new_column');
});
See: https://laravel.com/docs/master/migrations#creating-columns

Laravel Migrations change/update

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.

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