Mena
Mena

Reputation: 2029

ErrorException: Trying to get property 'id' of non-object

I wrote a unit test to update a record and when i try to run my test, it passes sometimes and fails at other times with the error

ErrorException: Trying to get property 'id' of non-object I have no idea why this is happening. Checked other post with similar title but nothing related to my case.

Here's the test

public function testUpdateBookRecord()
{
    // Select an existing user randomly & authenticate the user.
    $user = User::all()->random();
    Passport::actingAs($user);

    // Get any book belonging to the user.
    $selectedBook = Book::where('user_id', $user->id)->inRandomOrder()->first();

    // Update the book.
    $response = $this->json('PUT', '/api/books/'.$selectedBook->id, [
        'title'     => $this->faker->sentence(),
        'author'    => $this->faker->name()
    ]);

    $response->assertStatus(200);
}

And this is the controller responsible for the update

public function update(Request $request, Book $book)
{
    $validatedData = $request->validate([
        'title'     => 'required|unique:books',
        'author'    => 'required'
    ]);

    // Update book if the logged in user_id is the same as the book user_id
    if ($request->user()->id === $book->user_id) {
        $book->update($request->only(['title', 'author']));

        return new BookResource($book);
    } else {
        return response()->json(['error' => 'You do not have the permission for this operation'], 403);
    }
}

What is wrong with my code?

Upvotes: 1

Views: 3184

Answers (1)

yiqiao
yiqiao

Reputation: 77

you can write

User::inRandomOrder()->first();

or like a comment

$user['id'] instead of $user->id

Upvotes: 1

Related Questions