Placid
Placid

Reputation: 1448

Cannot access eloquent relationship in laravel test

I have the following relationship in User model and UserLevel model.

User:

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

UserLevel:

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

This works perfectly in Tinker as shown below:

enter image description here

But I can't seem to access the relationship in Laravel PHPUnit test. The following die and dump returns null:

class AddUserTest extends TestCase
{
  use DatabaseMigrations;

  /** @test */
  public function super_admin_can_view_add_user_form()
  {
    $super_admin_user = factory(User::class)->create([
      'username' => 'Test User 6',
      'user_level_id' => 7,
    ]);

    dd($super_admin_user->user_level);
  }
}

If I dd the $super_admin_user, it properly shows the created user. What am I doing wrong? How can I access the user_level in the test?

Upvotes: 2

Views: 1381

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111889

I can only assume, that in your model factory you create also related model, so if in your test you use:

$super_admin_user = factory(User::class)->create([
      'username' => 'Test User 6',
      'user_level_id' => 7,
    ]);

it won't work because. There is no UserLevel with id 7. So you should either create one in your test for example:

$user_level = factory(UserLevel::class)->create();
$super_admin_user = factory(User::class)->create([
      'username' => 'Test User 6',
      'user_level_id' => $user_level->id,
    ]);

or remove user_level_id from test completely:

$super_admin_user = factory(User::class)->create([
  'username' => 'Test User 6',
]);

(this is what you use in tinker)

Reference: https://laravel.com/docs/5.4/database-testing#writing-factories - section Relations & Attribute Closures

Upvotes: 1

Related Questions