Home > Mobile >  get data Factory Relationships for Laravel Testing
get data Factory Relationships for Laravel Testing

Time:04-23

according laravel-database-testing

I have a factory relationship for testing data, my code like this

 public function test_users_can_authenticate_using_the_login_screen()
    {
        $this->seed(RoleSeeder::class);
        $data = Organization::factory()
            ->count(1)
            ->has(User::factory()->count(2), 'users')
            ->create();

        $response = $this->post('/login', [
            'email' => $data->email,
            'password' => 'password',
        ]);

        $this->assertAuthenticated();
        $response->assertRedirect(RouteServiceProvider::HOME);
    }

How do I get the user->email data??, when i try $data->email or $data->users are not found?

CodePudding user response:

Have you add the relationship for both models (Organization & User)?

If yes, then you need to check specific which user you want to grab. Since it returns array of users.

try this for example

$data = Organization::factory()
            ->count(1)
            ->has(User::factory()->count(2), 'users')
            ->create();
$firstUserEmail = $data->users[0]->email;
  • Related