Home > front end >  Return data with pivot field Laravel Api
Return data with pivot field Laravel Api

Time:04-29

I want to return a role with permissions of it through pivot table, relationship, but when I write:

$role = $this->roleRepository->detail($id);
    $data = ([
        "role" => $role
    ]);

postman just return:

"data": {
        "role": {
            "id": 12,
            "name": "grand-admin"
        }
    }

I write:

        $role = $this->roleRepository->detail($id);
        $data = ([
            "role" => $role,
            "hasPermission" => $role->permissions
        ]);

Postman return:

"data": {
        "role": {
            "id": 12,
            "name": "grand-admin",
            "permissions": [
                {
                    "id": 1,
                    "name": "view_customer",
                    "pivot": {
                        "role_id": 12,
                        "permission_id": 1
                    }
                },
                {
                    "id": 1,
                    "name": "view_customer",
                    "pivot": {
                        "role_id": 12,
                        "permission_id": 1
                    }
                }
            ]
        },
        "hasPermission": [
            {
                "id": 1,
                "name": "view_customer",
                "pivot": {
                    "role_id": 12,
                    "permission_id": 1
                }
            },
            {
                "id": 1,
                "name": "view_customer",
                "pivot": {
                    "role_id": 12,
                    "permission_id": 1
                }
            }
        ]
    }

Problem is loop 2 times data of permission, how can I write to return only the upper part.

CodePudding user response:

You can either include the relationship in the repository logic (using with), or you can lazy-load the relationship like so:

$role = $this->roleRepository->detail($id);
$role->load('permissions');
$data = ([
    "role" => $role
]);

Lazy loading reference: https://laravel.com/docs/9.x/eloquent-relationships#lazy-eager-loading

OR

you can include permissions as a default loading relationship by defining the $with property in the model:

//your role model
class Role extends Model
{
    protected $with = ['permissions'];
...
}

Now your existing code should include permissions.

Default loading reference: https://laravel.com/docs/9.x/eloquent-relationships#eager-loading-by-default

  • Related