Extracting a pivot field one level up in laravel

  laravel, php, pivot

I have a many-to-many relationship with a pivot table. The two models in the relationship are Communities and Personas. In the pivot table, I have the IDs of the instances in relationship and an extra field called "member_count" to count the amount of members in that specific relationship. To access the member count field, I include the following function in my Community model to always have it returned:

public function personas()
{
    return $this->belongsToMany('AppPersona')->withPivot('member_count');
}

This results in the following being returned when I retrieve Communities:

{
    "id": "3304806f-9172-4690-b9b7-fa672319eaef",
    "name": "Some Community",
    "site_id": "ee09da48-9ba6-42a9-9f72-4d3ca06ffd2f",
    "internal_external": "internal",
    "created_at": "2020-09-11T14:36:23.000000Z",
    "updated_at": "2020-09-11T14:36:23.000000Z",
    "personas": [
        {
            "id": "1447bc79-f54e-49eb-b33d-acc1c43633e5",
            "name": "Some Persona",
            "created_at": "2020-09-11T14:41:27.000000Z",
            "updated_at": "2020-09-11T14:41:27.000000Z",
            "pivot": {
                "community_id": "3304806f-9172-4690-b9b7-fa672319eaef",
                "persona_id": "1447bc79-f54e-49eb-b33d-acc1c43633e5",
                "member_count": 10
            }
        },
        {
            "id": "ca53ec58-a4e8-4330-a5c3-8dea2235b01f",
            "name": "Another Persona",
            "created_at": "2020-09-11T14:41:15.000000Z",
            "updated_at": "2020-09-11T14:41:15.000000Z",
            "pivot": {
                "community_id": "3304806f-9172-4690-b9b7-fa672319eaef",
                "persona_id": "ca53ec58-a4e8-4330-a5c3-8dea2235b01f",
                "member_count": 5
            }
        }
    ]
},

I want to move the member_count field one level up to just be returned as part of the Persona object. Is there a way to do this built in to Laravel?

Source: Laravel

Leave a Reply