Im trying to create a seeder table that fills a table with some dummy data using the laravel ModelFactory. I keep getting this error and I'm out of ideas on fixing it.
The 'Race' Model
<?php
namespace App\Game;
use Illuminate\Database\Eloquent\Model;
class Race extends Model
{
//
public $timestamps = false;
protected $fillable = ['name','description','icon'];
}
File 2 The Model Factory File
$factory->define(App\Game\Race::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'description' => $faker->text,
'icon' => $faker->url,
];
});
File 3 The Seeder File
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class RacesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
factory(App\Game\Race::class, 10)->create()->each(function($u) {
$u->posts()->save(factory(App\Game\Race::class)->make());
});
}
}
I am getting the following error Call to undefined method Illuminate\Database\Query\Builder::posts()
This happens when I call 'php artisan db:seed'
It looks like you copied the seeder directly from the documentation. In the documentation's example, there is a User
model that is related to a Posts
model via a function posts
that is defined within the user model. See this documentation page for more information about why there's a posts
method on the User
model.
You have a Race
model that does not have Posts
related to it, indicated by the absence of posts
method inside your race model. Try simplifying the factory to this:
public function run()
{
//
factory(App\Game\Race::class, 10)->create();
}
This should create 10 race entries in your database for you. You would want to provide the closure passed to the each
method only if you intend to also create other models within the seeder that are related to each instance the factory creates, or do some other action for every instance (each
) of a Race
that gets created by the factory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With