DangerosoDavo DangerosoDavo - 1 month ago 28
PHP Question

Laravel 5.3 ModelFactory Seeder Call to undefined method Illuminate\Database\Query\Builder::posts()

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'

Answer

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.

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.

Comments