3
1

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 1 year has passed since last update.

【備忘録】Laravel8でfactoryを使うには

Last updated at Posted at 2020-12-05

##結論

{モデル名}::factory()->create();
複数作るときは
{モデル名}::factory->count(10)create();

##経緯

Laracastsのツイッタークローン作成の章で、
ファクトリーを使ってダミーのユーザーをデータベースへ登録するために

factory('App\User')->create()をtinker叩く

と指示があるものの、

PHP Fatal error: Call to undefined function factory() in Psy Shell code on line 1

とエラーを吐いてしまう。
これはLaravel8ではfactoryの使い方が以前のバージョンとは異なることが原因だった。

参考にしたページ→Please help: Call to undefined function factory()
ドキュメント→https://readouble.com/laravel/8.x/ja/database-testing.html

各モデルがHasFactoryトレートを持っている状態で生成されるように

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;//この部分
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Jetstream\HasTeams;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;//この部分
    use HasProfilePhoto;
    use HasTeams;
    use Notifiable;
    use TwoFactorAuthenticatable;

中略
    
}

HasFactoryトレート

<?php

namespace Illuminate\Database\Eloquent\Factories;

trait HasFactory
{
    /**
     * Get a new factory instance for the model.
     *
     * @param  mixed  $parameters
     * @return \Illuminate\Database\Eloquent\Factories\Factory
     */
    public static function factory(...$parameters)
    {
        $factory = static::newFactory() ?: Factory::factoryForModel(get_called_class());

        return $factory
                    ->count(is_numeric($parameters[0] ?? null) ? $parameters[0] : null)
                    ->state(is_array($parameters[0] ?? null) ? $parameters[0] : ($parameters[1] ?? []));
    }

    /**
     * Create a new factory instance for the model.
     *
     * @return \Illuminate\Database\Eloquent\Factories\Factory
     */
    protected static function newFactory()
    {
        //
    }
}
3
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?