0
2

More than 3 years have passed since last update.

【Laravel6.x以降対応】既存のDBからマイグレーションファイルを作成する方法

Posted at

既存のテーブルをLaravelで使用するときに、いちいち手書きでマイグレーションファイルを書くのは大変なので自動で生成したい。
migrations-generatorで出来るらしい。

しかしLaravel6.x以降には対応していない

Laravelで既存のDBからmigrationsファイルを作成する「migrations-generator」
https://qiita.com/busyoumono99/items/a7173ad6b9b041da09dd

6.x以降ではoscarafdev/migrations-generatorのリポジトリを使用する

そして、そのステップ1として、前回の既存のDBからmigrationファイルを自動作成のパッケージの紹介でした。
しかし、このパッケージ、残念ながらLaravel6.xでは互換性で使えない、と思ったら対応しているこれまたレポをフォークしたパッケージがありました。
https://github.com/oscarafdev/migrations-generator
捨てる神があれば、拾う神ありです。助けられます。

手順

1.oscarafdev/migrations-generatorをインストール

$ composer require oscarafdev/migrations-generator --dev  

2.マイグレーションファイル生成
既存のusers,password_resets,failed_jobs,migrationsのマイグレーションファイルは生成しないように設定。

$ php artisan migrate:generate --ignore"users,password_resets,failed_jobs,migrations"

3.使えるか確認

positionsテーブルを使えるようにしていきます。
Positionモデルを生成。

$ php artisan make:model Position

テーブル名を設定

Position.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Position extends Model
{
    protected $table = 'positions';
}

コントローラー作成

$ php artisan make:controller PositionController
PositionController.php
<?php

namespace App\Http\Controllers;

use App\Position;
use Illuminate\Http\Request;

class PositionController extends Controller
{
    public function index()
    {
        $positions = Position::all();
        var_dump($positions);
    }
}

ルーティング設定

web.php
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Auth::routes();

Route::get('/', 'HomeController@index')->name('home');

Route::get('/positions', 'PositionController@index')->name('positions.index');

無事取得できていた。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2