dimanche 18 octobre 2015

Laravel call to member function create() on a non-object

I'm trying to seed a database using some model factories but I'm getting error call to member function create() on a non-object

Below are my model factories:

$factory->define(App\Organisation::class, function ($faker) {
   return [
    'name' => $faker->company,
   ];
});

$factory->define(App\Department::class, function ($faker) {
   return [
    'name' => $faker->catchPhrase,
    'organisation_id' => factory(App\Organisation::class)->make()->id,
   ];
});

$factory->define(App\User::class, function ($faker) {
  return [
    'email' => $faker->email,
    'password' => str_random(10),
    'organisation_id' => factory(App\Organisation::class)->make()->id,
    'remember_token' => str_random(10),
  ];
});

In my seeder I'm using the following to create 2 organizations and a associate a user and a department to each organization and then to make a user the manager of that department:

factory(App\Organisation::class, 2)
        ->create()
        ->each(function ($o)
        {
            $user = $o->users()->save(factory(App\User::class)->make());

            $department = $o->departments()->save(factory(App\Department::class)->make());

            $department->managedDepartment()->create([
                'organisation_id' => $o->id,
                'manager_id' => $user->id,
            ]);


        });

However I'm getting fatalerrorexception call to member function create() on a non-object

I thought $department is an object?

My department model is as follows:

class Department extends Model
{

    protected $fillable = ['name','organisation_id'];

    public function organisation()
    {
        return $this->belongsTo('App\Organisation');
    }

    /* a department is managed by a user */
    public function managedDepartment()
    {
       $this->hasOne('App\ManagedDepartment');
    }
}

And my managedDepartment model is as follows:

class ManagedDepartment extends Model
{
    protected $table = 'managed_departments';


    protected $fillable = ['organisation_id', 'department_id', 'manager_id',];


    public function department()
    {
        $this->belongsTo('App\Department');
    }

    public function manager()
    {
        return $this->belongsTo('App\User');
    }
}

Can anyone help?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire