1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel 8.x Seeder生成で怒られる

Last updated at Posted at 2021-02-25

Seederでダミーデータを作成する際、グローバルヘルパや関数を使用する際の落とし穴があります。

php artisan make:seed UsersTableSeederで作成すると以下のSeederが生成されます。

UsersTableSeeder.php
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

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

ダミーデータをrunメソッド内に記述しSeederを実行するとヘルパや関数を使用している場合は怒られます。

UsersTableSeeder.php
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name'           => 'hoge',
            'password'       => Hash::make('hoge'),
            'remember_token' => Str::random(30),
        ]);
    }
}

#対処法
ファザードやヘルパを使用する際は宣言してあげる必要があるらしいです。

UsersTableSeeder.php
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;       //最初からある
use Illuminate\Support\Facades\DB;    //DBファザード使用の為追加
use Illuminate\Support\Facades\Hash;  //Hashファザード使用の為追加
use Illuminate\Support\Str;           //strメソッド使用の為追加

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name'           => 'hoge',
            'password'       => Hash::make('hoge'),
            'remember_token' => Str::random(30),
        ]);
    }
}

##参考
https://readouble.com/laravel/8.x/ja/helpers.html

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?