LoginSignup
0
0

More than 3 years have passed since last update.

Laravelディレクトリ構成+DBマイグレーション

Last updated at Posted at 2020-09-28

今回はLaravelディレクトリ構成+DBマイグレーションを説明していきます。

ディレクトリ構成

image.png

ディレクトリ名 役割
app アプリのメインとなるところ
bootstrap 初期処理やキャッシュなど
config アプリの設定
database データベース(マイグレーション)
public 画像、JS、CSSなど
resources bladeなど(HTML)
routes アプリのURL設定
storage セッションやログ
tests テスト用
vendor Comoposerの依存内容

マイグレーション

マイグレーションとは

SQLを直接使わなくても、データベースを管理できるLaravelの仕組みです。

マイグレーションファイル

マイグレーションファイルは「どんなテーブルを作るか」というテーブルの設計書です。設計書を作ったらそれを実行しなければテーブルはできないので、この実行にあたるのがマイグレーションです。

テーブル作成の流れ

1. マイグレーションファイルを生成
2. ファイルにテーブル定義を書く
3. マイグレーションファイルを実行して、DBに反映

ファイルの場所とファイル名ルール

image.png

ファイル生成コマンド

 $ php artsan make:migration create_users_table 

(例)カラム追加ver

$ add_カラム名_to_テーブル名_table

実行コマンド

$ php artisan migrate

マイグレーションの中身

・upとdownメソッド
 upが実行(作成)で、downが元に戻す(削除)
・Schemaファサードを使っている
 例) Schema::create テーブルを作成
・カラムの作成はBlueprintオブジェクトのtableメソッドを使う
 例) $table->string('name')名前カラムを作成

   public function up()//作成
    {
        if(!Schema::hasTable('blogs')) {//もしblogsというtableがなかったら
            Schema::create('blogs', function (Blueprint $table) {
                $table->id();//idのカラム
                $table->string('title',100);//titleというカラムをstring型で100文字の制限をつけた状態で作る
                $table->text('content');//contentというカラムをtext型で作る
                $table->timestamps();
            });
        }

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()削除
    {
        Schema::dropIfExists('blogs');
    }

追加したいカラムなどを書き終えたらmigrateしていきます。

$ php artisan migrate

終わりに

参考サイトを貼らせて頂きます。

公式ドキュメント
https://readouble.com/laravel/7.x/ja/migrations.html

参考サイト
https://www.youtube.com/watch?v=wkW1spp_LO8

0
0
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
0