phplaravellaravel-8tinker

Laravel 8 BadMethodCallException


I am learning laravel 8, I keep getting this error

   BadMethodCallException 

  Call to undefined method App\Models\Question::factory()

  at C:\Users\USER\Desktop\laravels\qna\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php:50
     46▕      * @throws \BadMethodCallException
     47▕      */
     48▕     protected static function throwBadMethodCallException($method)
     49▕     {
  ➜  50▕         throw new BadMethodCallException(sprintf(
     51▕             'Call to undefined method %s::%s()', static::class, $method
     52▕         ));
     53▕     }
     54▕ }

  • Bad Method Call: Did you mean App\Models\Question::toArray() ?

  1   C:\Users\USER\Desktop\laravels\qna\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php:36
      Illuminate\Database\Eloquent\Model::throwBadMethodCallException("factory")

  2   C:\Users\USER\Desktop\laravels\qna\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:1993
      Illuminate\Database\Eloquent\Model::forwardCallTo(Object(Illuminate\Database\Eloquent\Builder), "factory")

I am in the DatabaseSeeder.php file and I think the issue is coming from this code:

public function run()
{
    \App\Models\User::factory(3)->create()->each(function($u) {
        $u->questions()
          ->saveMany(
            //   factory(App\Question::class, rand(1,5))->make()
            \App\Models\Question::factory(rand(1,5))->make()
          );
    });
}

I get something similar after running this command in tinker:

>>> \App\Models\Question::factory(3)->make();

Link to repo is here Any pointer will be appreciated!


Solution

  • So, in your model you need the trait 'HasFactory' before you can use it