Skip to content
Advertisement

Laravel API Resourse returning relation only on ‘collection’ method

guys I’m new to Laravel. I currently building an API, and I have a couple of endpoints (the one that we will discuss are the Get All Tasks and Get Single Task)

The problem is that whenever I call the Get All Tasks endpoint it returns me the task resource + the user resource there. However when I call the Get Single Task endpoint it only returns me the TaskResource without the User inside of it. Any idea ?

Here is the code for the resourses

class TaskResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  IlluminateHttpRequest  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'estimate' => $this->estimate,
            'status' => $this->status,
            'type' => $this->type,
            'user' => new UserResource($this->whenLoaded('user'))
        ];
    }
}

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  IlluminateHttpRequest  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'avatar' => $this->avatar,
            'tasks' => TaskResource::collection($this->whenLoaded('tasks'))
        ];
    }
}

And here is how I get the Tasks in the controller. https://prnt.sc/16q0rlh

Advertisement

Answer

The reason was that I was missing the ‘with(‘user’)’ before the ‘findOrFail’ in my controller so ->

/**
     * Description: Get single task
     * Method: GET
     * api/tasks/{id}
     * @param TaskRequest $request
     */
    public function actionGetTask(Request $request, $id) {
        try {
            return new TaskResource(Task::with('user')->findOrFail($request->route('id')));
        } catch (Exception $ex) {
            return Response::json([
                'success' => false,
                'message' => 'There is no such id in the DB'
            ], 400);
        }
    }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement