【问题标题】:ErrorException: Trying to get property 'id' of non-objectErrorException:试图获取非对象的属性“id”
【发布时间】:2019-03-10 14:51:25
【问题描述】:

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

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

我的代码有什么问题?

【问题讨论】:

  • 有时您的数据库中是否可能没有任何用户?
  • 或这里$selectedBook->id。那么异常的行号到底是什么。
  • @krisanalfa 不,它实际上返回了一个用户,我可以从dd($user)看到它
  • 你能告诉我dd($user)的结果吗?
  • 这是一个数组。因此,您可以使用$user['id'] 而不是$user->id 访问它

标签: php laravel phpunit laravel-5.6


【解决方案1】:

你可以写

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

或喜欢评论

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

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 2020-09-30
    • 1970-01-01
    相关资源
    最近更新 更多