0

i try to build a customized response in my resource like this:

    class ApplicationResource extends JsonResource
    {
        /**
         * Transform the resource into an array.
         *
         * @param  \Illuminate\Http\Request $request
         * @return array
         */
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'sort'=> $this->sort,
                'is_seen' => $this->is_seen,
                'name' => $this->name,
                'position' => $this->position,
                'company' => $this->company,
                'education' => $this->education,
                'degree' => $this->degree,
                'phone' => $this->phone,
                'university' => $this->university,
                'cv_folder_id' => $this->cv_folder_id,
                'cv' => route('applications.cvShow', ['candidateCv' => $this->candidate_cv]),
                'comments'=>   ApplicationCommentsResource::collection($this->applicationComments),
                'ratingFields'=>   ApplicationRatingsResource::collection($this->applicationRatings()->get()),
                'jobPostRatingFields' =>   JobPostRatingFieldsResource::collection($this->jobPost->jobPostRatingFields),

            ];
        }
    }

but i just get errors. the error i get is:

Call to a member function first() on null

i dont know how to build my response that if the collection is empty i dont get any error?

Karan
  • 1,146
  • 1
  • 10
  • 24
Vahid Saberi
  • 105
  • 1
  • 2
  • 12

2 Answers2

1

That simply means that you want to retrieve value that does not exist. You can make simple condition like that:

if(is_null($this->sort)){
    return "-";
}

Good luck!

Adam Kozlowski
  • 5,606
  • 2
  • 32
  • 51
0

I'm pretty sure the relationship is the problem. But since there is not enough information, first of all find out in which line the error is, then check the relationships.


For example:

'comments'=> ApplicationCommentsResource::collection($this->applicationComments)

Model Application must have relationship applicationComments

iamfree
  • 1
  • 2