2

I have a ready database created in MySQL. Now I created a new Laravel 6 project. Is it possible to add the tables in MySQL database into the laravel migrations without losing the data? and is there a way to generate a migration from MySQL to laravel ?

Mobeen Sarwar
  • 514
  • 5
  • 23
  • 1
    [Xethron Migrations Generator](https://github.com/Xethron/migrations-generator) should solve your problem. It converts a mysql database to laravel migration scripts – julianstark999 Mar 20 '20 at 08:47
  • Yeah you are right and I tried it before I ask, but it only works with laravel 5 – Hikmat Mohammed Mar 20 '20 at 08:53
  • 1
    It seems laravel have no this command,Maybe you need to do it by yourself. Use `mysqldump -u root -p --no-data yourdatabase > schema.sql` and read every tables in schema.sql, then convert them into the migration dir. – TsaiKoga Mar 20 '20 at 09:43
  • 1
    So you could create a dummy laravel 5 app to generate the migrations and copy them to your laravel 6/7 app – julianstark999 Mar 20 '20 at 11:02

4 Answers4

1

Firstly you have to create the migrations (https://laravel.com/docs/6.x/migrations)

php artisan make:migration

Next run

php artisan migrate

and finaly import your data to the new tables

  • 1
    I think the OP is asking about tables that existed before creating the Laravel application. – Rwd Mar 20 '20 at 08:47
  • I just did the "php artisan make:migration" and i got "Not enough arguments (missing: "name")." – Hikmat Mohammed Mar 20 '20 at 08:47
  • Exactly @Rwd , The tables are existed before creating the Laravel application. – Hikmat Mohammed Mar 20 '20 at 08:49
  • 1
    In this case, you have to make use of `if (!Schema::hasTable('users')) {...}` and wrap it around the schema creation. If not, `php artisan migrate` will run in an error if the table already exists. – Dimitri Mostrey Mar 20 '20 at 09:14
1

if you want to change some columns from your table.. you can create

php artisan make:migration 

and on your migration, you can write code :

Schema::table('users', function (Blueprint $table) {
    $table->string('name', 50)->change();
});

be sure to add the doctrine/dbal dependency to your composer.json file.

composer require doctrine/dbal
1

You simply have to check if the table exists already or not. Do something like this in your Migration:

if(!Schema::hasTable('TABLE_NAME')) {
    Schema::create('TABLE_NAME', function (Blueprint $table) {
        $table->bigIncrements('id');
        ...
    }
}

Official docs: https://laravel.com/docs/6.x/migrations#creating-tables

Qumber
  • 13,130
  • 4
  • 18
  • 33
1

first you have to create table using cli php artisan migration:create_name_table then run the command php artisan migrate