adrienpsn's avatar

Trying to get property 'name' of non-object

  • Laravel Version: 5.7.*
  • PHP Version: 7.2.9
  • Database Driver & Version: sqlite 7.2.9

Description:

When I launch my test, I have this error : ErrorException: Trying to get property 'name' of non-object

Code

My UserTest:

/**
 * Disable exception handling
 * Act like a connected user
 * Seed database with seeder
 * Perform a GET request on `api/users`
 * Check if the response is successful (200)
 * Check if the response contains 10 records
 * @test
 */
public function a_user_is_logged_in_and_will_search_for_users_that_are_returned_in_a_json_format()
{
    $this->withoutExceptionHandling();

    Passport::actingAs(factory(User::class)->create(), ['*']);

    $role = factory(Role::class, 1)->create();

    $users = factory(User::class, 5)->create([
        'role_id' => $role[0]->id
    ]);

    $response = $this->json('GET', 'api/users');

    $response->assertSuccessful()
        ->assertSuccessful()
        ->assertJsonCount($users->count());
}

My UserFactory:

$factory->define(App\User::class, function (Faker $faker) {
    $first_name = $faker->firstNameMale;
    $last_name = $faker->lastName;
    $full_name = $first_name . ' ' . $last_name;
    $username = strtolower(str_replace(' ', '.', $first_name . ' ' . $last_name));

    return [
        'full_name' => $full_name,
        'username' => $username,
        'email' => $username . '@' . $faker->domainName,
        'password' => bcrypt('Password'),
        'role_id' => $faker->numberBetween(1, 4)
    ];
});

My RoleFactory:

$factory->define(App\Role::class, function (Faker $faker) {
    $roles = ['User', 'Technician', 'Supervisor', 'Administrator'];
    return [
        'name' => $faker->randomElement($roles)
    ];
});

My UserCollection (I use this to display my data in a JSON format):

public function toArray($request)
{
    return [
        'id' => $this->id,
        'full_name' => $this->full_name,
        'username' => $this->username,
        'email' => $this->email,
        'role' => $this->role->name,
        'created_at' => $this->created_at->diffForHumans(),
        'updated_at' => $this->updated_at->diffForHumans()
    ];
}

The line 'role' => $this->role->name create the error: ErrorException: Trying to get property 'name' of non-object

0 likes
1 reply

Please or to participate in this conversation.