ErrorException:尝试获取非对象的属性“ id”

时间:2018-10-05 06:49:05

标签: php laravel phpunit laravel-5.6

我写了一个单元测试来更新一条记录,当我尝试运行测试时,它有时通过并在其他时间失败并出现错误

  

ErrorException:尝试获取非对象的属性“ id”   我不知道为什么会这样。检查了其他标题相似但与我的案件无关的帖子。

这是测试

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);
}

这是负责更新的控制器

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);
    }
}

我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

你可以写

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

或喜欢评论

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