saber tabatabaee yazdi
saber tabatabaee yazdi

Reputation: 4959

Inject/merge medialibrary items into belongtomany relation in laravel

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?

Upvotes: 0

Views: 34

Answers (1)

Khayam Khan
Khayam Khan

Reputation: 1235

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);

Upvotes: 1

Related Questions