laravel 8 migration deletes worldcities table - laravel

I have a table called worldcities that has all the cities on this planet, but everytime I migrate:fresh --seed then all tables are deleted including this one. Also, it takes forever to put the cities back since it's about 1gb.
What would be the best way to use php artisan migrate:fresh --seed without also deleting the worldcities table? I have tried many options, but none is working yet.
I read something about --ignore=worldcities, but that doesn't work with fresh. So it's not taking me anywhere this far.

Instead of using migrate:fresh you can use migrate:refresh, which uses down() method of the migration.
So in down method comment dropping table: Schema::dropIfExists(),
Then in up method, check that table is already exists or not:
if (Schema::hasTable('table_name')) {
return;
}
For seeding simply check that record exists or not, for preventing duplication. Or for fewer query, just create if table doesn't have any records.

Related

How to run Laravel Migrations, then Seeders, then more Migrations

I am re-building my Laravel app and, in the process, redesigning the data model.
I have a subset of my Migrations (35) I need to run to create the data model in the new app.
Then, I need to run some Seeders to populate the new tables.
Some of the new tables (12) have a column "old_id" where I place the "id" from the old data model to handle foreign keys/joins. I run a series of Update statements to change the foreign key values from the "old_id" to the new id.
Then, I want to run additional Migrations (12) that drop the "old_id" columns.
Here are the commands I'm running currently that do everything for me - clear DB, run migrations, populate data, and update keys.
php artisan migrate:reset
php artisan migrate:fresh --seed --seeder=DatabaseSeeder
I'm trying to find a way to only run a portion of my Migrations prior to executing DatabaseSeeder, and then run the remaining Migrations after (or as the last step of) the DatabaseSeeder.
Contents of DatabaseSeeder::class:
public function run()
{
$this->call([
// Seeders to populate data
UserSeeder::class,
AssociationSeeder::class,
... lots more classes ...
// Last Seeder class executes Update statements to update foreign keys
DatabaseUpdateSeeder::class,
]);
Thank you!
I ended up following the advice of the comment on the original post. While my previous "answer" also works, this is the right way to do it; separating round 1 and round 2 Migrations, and not executing Seeders from a Migration.
Here are my 2 commands (could be 3 if I wanted a separate command in the middle that only executes the Seeder), but adding the Seeder on the end of the command is supported syntax.
php artisan migrate:fresh --path=/database/migrations/batch-one --seed --seeder=DatabaseSeeder
php artisan migrate --path=/database/migrations/batch-two
I was able to achieve this by creating a Migration that calls my DatabaseSeeder. Here is how: https://owenconti.com/posts/calling-laravel-seeders-from-migrations
Then, after that Migration, I just have an additional Migration(s) to drop the "old_id" columns.
I also want to call out the comment from Tim on my original post with an alternative that would also work, but required multiple statements from the command line.

Laravel: Running a database migration on a production server

I have a local repo for development and a production server in Laravel.
When I work locally, as the project grows, so does the DB. Therefore I keep adding new migrations that sometimes change existing tables. Locally I can refresh / recreate tables and seed without worrying.
However when I want to update the production DB where actual data is stored, what's the best method? If I need to update an existing table I cannot just drop and recreate it, as data would be lost. And if I run the migration directly, I get an error like "table already exists". So I end up manually adding the fields in the DB, which I don't think it's the best way to go.
As already mentioned, you can create migrations to update the columns without dropping the tables. And the 'Modifying columns' docs provide a clear explanation for this. However that is docs for modifying columns, if you want to modify tables instead of columns, you can use the 'Updating tables' docs
This uses the SchemaBuilder to do various things, for example, adding columns in an existing table:
Schema::table('table_name'), function ($table) {
$table->string('new_column')->after('existing_column');
// however you can leave the ->after() part out, this just specifies that the
// new column should be insterted after the specified column.
});
Or delete a column from an existing table
Schema::table('table_name'), function ($table) {
$table->dropColumn('new_column');
});
You can also rename but I'll leave it to you to explore the docs further.

Current model is incompatible with old migrations

I have following sitation (I will describe it as history line):
I setup project witch User model (and users table) with migration file A
After some time i add user_modules table many-to-many and I was force to initialize this array during schama update in migration file B. I do it by
User::chunk(100, function($users) {
foreach ($users as $user) {
$user->userModule()->create();
}
});
After some time i need to update User model and table by add soft-delete (column delete_at) in migration file C and field $dates=['deleted_at'] in User model.
Then I develop system and add more migrations but at some point new developer join to our team and he must build DB schema from scratch so he run php artisan:migrate but he get error in migration file B:
[Illuminate\Database\QueryException (42S22)]
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'users.deleted_at' in 'where clause' (SQL: select * from users
where users.deleted_at is null order by users.id asc limit 100
off set 0)
So the current User model is incompatible witch migration file B
How to deal with that situation?
Where I made mistake and what to do to prevent such situation in future?
This is because of Soft Deletes. When you add the trait SoftDeletes to a model, it will automatically add where users.deleted_at is null to all queries. The best way to get around this is to add withTrashed() to your query in migration B.
To do this, change your query in migration B to look like the following. This should remove the part where it's trying to access the non existent deleted_at column. This migration, after all, is not aware that you want to add soft deletes later on, so accessing all users, including those that are trashed, makes perfect sense.
User::withTrashed()->chunk(100, function($users) {
foreach ($users as $user) {
$user->userModule()->create();
}
});
You could always comment out the SoftDelete trait on the user model before running the migrations also, but that's a temporary fix since you'll need to explain it to all future developers. Also, it can be very handy to run php artisan migrate:fresh sometimes. You don't want to have to remember to comment out the trait each time, so adding withTrashed() seems like the most desirable solution to me.
As a final note, I highly suggest NOT adding seeds to your migrations. Migrations should ONLY be used for schema changes. In cases like this, I would use a console command, or a combination of console commands.
For example, you could make a console command that gets triggered by php artisan check:user-modules. Within this command, you could have the following which will create a user module only if one does not yet exist.
User::chunk(100, function($users) {
foreach ($users as $user) {
if (!$user->userModule()->exists()) {
$user->userModule()->create();
}
}
});
You should be able to run this command at any time since it won't overwrite existing user modules.
Alternative answer: In such situation when we need to generate or transform some data after db schema change - we should NOT use Models (which can independently change in future) but instead use inserts/updates:
DB::table('users')->chunkById(100, function ($users) {
foreach ($users as $user) {
DB::table('user_modules')->insert(
['user_id' => $user->id, 'module_id' => 1]
);
}
});
As it is written in laravel documentation, seeders are designed for data seeding with test data but not for data transformation - so migration files are probably good place to put transformation code (which can generate or change some production data in DB after schema update)
Laravel includes a simple method of seeding your database with test data using seed classes.
Add this to your old migration queries
use Illuminate\Database\Eloquent\SoftDeletingScope;
User::withoutGlobalScope(new SoftDeletingScope())

Laraver - display model structure

Im learning laravel.
My question is about some simple way do display model structure. I have little experience with django and as i remember, structure for each model was placed inside model files.
Yet in laravel, i need to put starting structure inside migration file:
$table->increments('id');
$table->timestamps();
$table->string('name')->default('');
Then if i want to add some new field, i will place this field in next migration file, etc.
So, is there any way to see some kind of summary for model? Maybe some bash command for tinker?
There are a bunch of options for you to choose from.
If you would like to show a summary of a model while you are in tinker, you can call toArray() on an instance of your model.
Ex:
$ php artisan tinker;
>>> $user = new App\User(['email' => 'john#doe.com', 'password' => 'password]);
>>> $user->toArray();
If you are trying to see a summary of a model displayed on your webpage, just var_dump or dd(...) an instance of your model after calling toArray() on it, and you'll get the same result as above, just in your web browser.
If you are looking for a way to show the table structure without creating any Model instances, you can display the table structure in your terminal, the exact command depending on what database you are using.
For example in MySQL you would do something like:
mysql> show COLUMNS from USERS;
It might also be a good idea to get a GUI app, I like Sequel Pro (for Mac).
P.S. I would just add that you should only have separate migrations for adding new fields when you are already in production and can't lose data from your database. While you are still in development and don't care about your data, it is much better to call php artisan migrate:rollback, add the new field to your create migration, and then php artisan migrate again, rather than making tons of new migration files.

Laravel 5 Composer update fails

After upgrading a Laravel project from 5.0 to 5.1.x, I can not run a composer update correctly.
The app itself works fine and no problems, but will need composer to work.
This is the error I am receiving after running sudo composer update
[LogicException]
The command defined in "Illuminate\Database\Console\Migrations\MigrateMakeCommand" cannot have an empty name.
Script php artisan clear-compiled handling the pre-update-cmd event returned with an error
[RuntimeException]
Error Output:
When trying to debug the file Illuminate\Database\Console\Migrations\MigrateMakeCommand I can not find any noticable error.
Any help would be greatly appreciated.
Laravel is giving its best to maintain the relationship first of all you need to have 2 model or you can say two table for relation and the respestive columns now you need to specify whether it has relation of one to one or one to many or many to many then you can simple specify it on model. As your tables are not specific tables so you can see the example like relation between users table and questions table relation here is one to many . One user can have many question while one question is belong to the user now In my Questions model the realtion looks like public function user() {
return $this->belongsTo('App\User');
}
now in the user model my code looks like
return $this->hasMany('App\Questions');
}
be sure you have maintained foreign key while migrating :) for more you can see here http://laravel.com/docs/5.0/eloquent#relationships hope this would help

Resources