Petro Gromovo
Petro Gromovo

Reputation: 2243

Using whenLoaded in Resource Collection I got error

In laravel 6 app I have a Resource Collection, which works ok for me :

class UserSkillCollection extends ResourceCollection
{
    public static $wrap = 'user_skills';

    public function toArray($request)
    {

        return $this->collection->transform(function($userSkill){
            return [
                'id' => $userSkill->id,
                'user_id' => $userSkill->user_id,
                'user_name' => $userSkill->user_name,
                'skill_id' => $userSkill->skill_id,
                'skill_name' => $userSkill->skill_name,
                'rating' => $userSkill->rating,
                'created_at' => $userSkill->created_at,
            ];
        });

    }

except when some fields are defined, like user_name, I have keys with null values.

To get rid of them I tried to use whenLoaded, but with line :

'user_id' => $this->whenLoaded('user_id'),

I got error :

"message": "Method Illuminate\\Support\\Collection::relationLoaded does not exist.",

Which way is valid ?

MODIFIED : I added relations in models and making :

  'user' => $userSkill->whenLoaded('user'),

or

  'user' => $this->whenLoaded('user'),

I got error :

Call to undefined method App\UserSkill::whenLoaded(

I suppose this error as I call it from Collection. How correctly ?

Thanks!

Upvotes: 1

Views: 2210

Answers (1)

Spholt
Spholt

Reputation: 4042

relationLoaded() is a method inherited from the HasRelationships trait on Illuminate\Database\Eloquent\Model.

Your code is trying to access it on a instance of an Illuminate\Support\Collection.

Try accessing the relationship user rather than it's key user_id. Like so:

$this->whenLoaded('user')

Upvotes: 2

Related Questions