LoginSignup
0
2

More than 1 year has passed since last update.

Laravelで簡単なCMSを作成(データベース作成)

Last updated at Posted at 2021-05-03

Laravelで簡単なCMSを作ってみます。
環境構築は以下の記事を参考にどうぞ。

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

テーブル構成・定義はCakePHPのチュートリアルで紹介されているものを拝借し、3つテーブルを作成します。Laravelにはマイグレーションというデータベースの管理機能が提供されているので、これを使用します。

まずはartisanコマンドを使用してマイグレーションファイルを生成します。

php artisan make:migration create_articles_table
php artisan make:migration create_tags_table
php artisan make:migration create_article_tag_table

テーブル定義作成

作成されたマイグレーションファイルに各テーブルの定義を加えていきます。

database/migratations/create_articles_table
<?php

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

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id');
            $table->string('title', 255);
            $table->string('slug', 191);
            $table->text('body');
            $table->boolean('published')->default(false);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}
database/migratations/create_tags_table
<?php

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

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

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tags');
    }
}
database/migratations/create_article_tag_table
<?php

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

class CreateArticleTagTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('article_tag', function (Blueprint $table) {
            $table->integer('article_id');
            $table->integer('tag_id');
            $table->timestamps();
        });
    }

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

マイグレーションファイルが作成できたらmigrateArtisanコマンドを実行してデータベースに反映させます。

php artisan migrate

これだけでテーブルを作成できます。

おまけ

テーブル作成後にテストデータを追加したい場合は、Laravelのシーディングを利用します。

テストデータとしてusersテーブルにuserを作成してみます。

シーダーファイルを作成

マイグレーションと同様にartisanコマンドを実行してシーダファイルを作成します。コマンド実行後database/seedersにシーダファイルが生成されます。

php artisan make:seeder UserSeeder

シーダファイルが生成されたら、データ挿入処理を追加します。

database/seeders/UserSeeder.php
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name' => 'john',
            'email' => 'john@gmail.com',
            'password' => Hash::make('MyPassword'),
        ]);

        DB::table('users')->insert([
            'name' => 'jack',
            'email' => 'jack@gmail.com',
            'password' => Hash::make('MyPassword'),
        ]);
    }
}

シーダの呼び出し

artisanコマンドを使用して個別にシーダファイルを実行することができますが、DatabaseSeederクラスのcallメソッドにシードクラスを登録することで、シーダファイルが複数になっても一括で実行できるようになります。

database/seeders/DatabaseSeeder.php
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // \App\Models\User::factory(10)->create();
        $this->call([
            UserSeeder::class,
        ]);
    }
}

シーダの実行

db:seed ArtisanコマンドでDatabase\Seeders\DatabaseSeederクラスを呼び出しシーディングを実行します。これによりテストデータが登録できます。

php artisan db:seed

テーブルの中身を確認したいとき、vscodeの拡張機能を使用すれば簡単にテーブルデータを確認することができます。

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