Inject/merge medialibrary items into belongtomany relation in laravel

30 Views Asked by At

I have json like this:

"member_skills": [
    {
        "id": 69,
        "skill_type_id": 6,
        "title": "Piano",
        "created_at": null,
        "updated_at": null,
        "pivot": {
            "member_id": 4,
            "skill_id": 69,
            "description": "description",
            "other_skill": null
        }
    }
],

The relation is this:

public function memberSkills(): BelongsToMany
{
    return $this->belongsToMany(Skills::class, MemberSkill::class, null, 'skill_id')->withPivot("description", "other_skill", "name");
}

I have media library and I want to inject those media library items in subset of any skills.

Every skill has medias.

How can I do it?

1

There are 1 best solutions below

0
Khayam Khan On

I am assuming that you have properly set the Skill model to interact with Media.

You can't simply use with('media') in your BelongsToMany relationship definition. Instead, you can manually append media to your skills when you're fetching them like,

$member = Member::with('memberSkills')->find($memberId);

$member->memberSkills->each(function ($skill) {
    $skill->media = $skill->getMedia('media_collection');
});

And then you can return the skills for example is Json Response,

return response()->json($member->memberSkills);