Call to a member function first() on null in laravel resource

Vahid Saberi picture Vahid Saberi · Nov 4, 2019 · Viewed 7.9k times · Source

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?

Answer

Adam Kozlowski picture Adam Kozlowski · Nov 4, 2019

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!