Skip to content

Instantly share code, notes, and snippets.

@yano
Last active January 21, 2018 07:35
Show Gist options
  • Save yano/dfd42ca017fd7e6a24f13efb1c813dfd to your computer and use it in GitHub Desktop.
Save yano/dfd42ca017fd7e6a24f13efb1c813dfd to your computer and use it in GitHub Desktop.
PHPはじめてのフレームワーク Laravel 5.5対応 ステップ2 の私的まとめ

Bookにユーザ情報をつける

  • ユーザごとにBookを表示することができる
  • 登録したユーザを参照することができる

Book にユーザIDの項目を付加する

migrationファイルで、追加。

    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->increments('id');

            $table->integer('user_id'); # これ
            
            $table->string('item_name');
            $table->integer('item_number');
            $table->integer('item_amount');
            $table->datetime('published');

            $table->timestamps();
        });
    }

Seederの利用

php artisan make:seeder  BooksTableSeeder

BooksTableSeeder内で以下のように記載する。

    public function run()
    {
        // ここに追加
        $faker = Faker\Factory::create('ja_JP');

        for ($i=0; $i<50; $i++) {
            App\Book::create([
                'user_id' => $faker->numberBetween(1, 5),

                'item_name' => $faker->word(), // 文字列
                'item_number' => $faker->numberBetween(1, 3), // 文字列
                'item_amount' => $faker->numberBetween(1, 6), // 文字列
                'published' => $faker->dateTime('now'), // 文字列
                'created_at' => $faker->dateTime('now'), // 文字列
                'updated_at' => $faker->dateTime('now'), // 文字列
            ]);
        }
    }

Fakerの記法は以下を確認。

https://github.com/fzaninotto/Faker

Seederの実行

php artisan db:seed --class=BooksTableSeeder

localeの変更

/config/app.phpのロケールを変更することで日本語対応になる。

'locale' = 'ja',

Validationエラーの日本語化。

resources/lang/ja/validation.phpを新規作成。

下記、URLにあるコードをコピペ。

laravel 5.3

https://gist.github.com/oppara/5160fcac9db0e3f8fbaf71da7ade10be

laravel 5.5

https://gist.github.com/yukimunet/7d65e2272c70b804f73a4dc68cb5f1c0

resource/lang/en 内の内容を翻訳して、resource/lang/ja におけば、日本語化が可能。

参考

https://www.amazon.co.jp/dp/B06XZDP92Y/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment