为特定用户显示单个资源

Displaying single resource for specific user

我想在 API 应用程序中为特定用户显示单个预订资源,当对这条路线 get 发出请求时 localhost:8000/api/user/{user}/reservations/{reservation} 然后用户应该能够查看预订详情。

尝试通过向 localhost:8000/api/user/1/reservations/1 发出获取请求进行测试,但没有返回任何内容。

这是应该返回预订的控制器方法

<?php

namespace App\Http\Controllers;

use App\User;
use App\Reservation;

...

public function showReservation(User $user, Reservation $reservation)
{
    if (auth()->user() == $user) {

        $reservedProduct = new ReservationResource(Reservation::where('user_id', $user->id)->where('id', $reservation->id)->first());

        return response()->json(['reservation' => $reservedProduct]);
    }
}

谁能告诉我为什么我的代码不起作用?请记住,实际上有该用户制作的保留产品

你不应该直接比较两个 eloquent 模型,如果你想检查它们是否是同一模型,你可以检查 id 是否相等:

if (auth()->user()->id == $user->id)

或者更好地使用 is() 函数:

if (auth()->user()->is($user))

您可以在官方阅读更多模型比较documentation

您的控制器函数没有返回任何内容,因为 if clause 始终是 false

终于解决了,事实证明解决方案很简单。

所以首先我更正了比较 auth()->user()$user 的方式。

然后因为我正在寻找一个单独的预订实例,其 ID 已经在这样的路线中传递 localhost:8000/api/v1/user/{user}/reservations/{reservation} 我只需要在资源中传递预订而不是查询我正在做。

解决方案代码是

if (auth()->user()->is($user)) {

    $reservedProduct = new ReservationResource($reservation);

    return response()->json(['reservation' => $reservedProduct]);
}