LoginSignup
2
1

More than 3 years have passed since last update.

Laravel ~テーブルとデータの作成~

Last updated at Posted at 2021-04-25

はじめに

Laravelの勉強を開始して、約3ヶ月経ったので備忘録として記事に残しておきます。

動作環境

PHP Laravel MySQL
7.1.19 5.6.27 5.7.22

データベース作成

MySQLで今回使用するデータベースを作成します。

mysql > create database データベース名;

.envファイル編集

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=データベース名      
DB_USERNAME=MYSQLのユーザー名
DB_PASSWORD=設定しているパスワード

これで作成したデータベースをLaravelで使用できる。

migrationファイル作成

artisanコマンドで下記を実行するとdatabase/migrations/にmigrationファイルが作成される。

php artisan make:migration create_books_table --create=books
yyyy_mm_dd_xxxxxx_create_books_table.php
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

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

このファイルにカラムを追加していく。

カラム作成例

記載方法 情報
$table->increments(カラム名); 主キー
$table->integer(カラム名); INT型
$table->string(カラム名, 文字数); VARCHAR型
$table->text(カラム名); TEXT型
$table->dateTime(カラム名); 日付と時間
$table->timestamps(カラム名); created_at, update_at
$table->softDeletes(カラム名); deleated_at

編集終わったら、マイグレーションを実行する。
そうするとbooksテーブルが作成される。

php artisan migrate

特定のmigrationファイルをマイグレーション実行する際は下記のコマンドを実行する。

php artisan migrate:refresh --step=1  --path=/database/migrations/yyyy_mm_dd_xxxxxx_create_books_table.php 

作成したテーブルを削除する際はロールバックすれば良い。

php artisan migrate:rollback

初期データ作成

今回は、seederという機能を使用して初期データを作成していく。
ますは、seederファイルの作成から始めます。

php artisan make:seeder BooksTableSeeder

上記コマンド実行することによってdatabase/seeds/以下に、BooksTableSeeder.phpが作成される。

BooksTableSeeder.php
<?php

use Illuminate\Database\Seeder;

class BooksTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
       //
    }
}

上記のrunメソッド内に追記していく。
例えば、、、
カラム名 => 初期データ で記述していく

BooksTableSeeder.php
    public function run()
    {
        DB::table('books')->truncate();  //データのクリア
        DB::table('books')->insert([     //booksテーブルに登録するレコードを配列で記述していく
            [
                'name'    => 'コロコロコミック',
                'created_at' => Carbon::create(2018, 1, 1),
                'updated_at' => Carbon::create(2018, 1, 4),
            ],
            [
                'name'    => 'ゼクシィ',
                'created_at' => Carbon::create(2018, 2, 1),
                'updated_at' => Carbon::create(2018, 2, 5),
            ],
        ]);
    }

上記でCarbonという日付操作のライブラリを使用している。
使用のためには、use Carbon\Carbon;の記述必須。

記述終わったら、作成したseederファイルで初期データを投入するために同じディレクトリにある
DatabaseSeeder.phpに以下のように追記する。

DatabaseSeeder.php
<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(BooksTableSeeder::class); //この部分を追記
    }
}

最後に下記のコマンドを実行することで、初期データ作成完了!!

php artisan db:seed

参考

https://readouble.com/laravel/5.5/ja/migrations.html
https://readouble.com/laravel/5.5/ja/seeding.html

2
1
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
2
1