in my Laravel app I have three database tables called users, projects and roles. There is m:n relation between them so I have also pivot table called project_user_role. Pivot table contains user_id, project_id and role_id columns. See image for screenshot from MySQL Workbench.
My User, Project and Role models got defined belongsToMany relation like that:
- //User model example
- public function projects()
- {
- return $this->belongsToMany('App\Library\Models\Project', 'project_user_role')->withPivot(['user_id','role_id']);
- }
Now I can easily get projects of authenticated user like that:
- $user = Auth::user();
- $projects = $user->projects;
Response of this looks like that:
- [
- {
- "id": 1,
- "name": "Test project",
- "user_id": 1,
- "created_at": "2018-05-01 01:02:03",
- "updated_at": "2018-05-01 01:02:03",
- "pivot": {
- "user_id": 2,
- "project_id": 17,
- "role_id": 1
- }
- },
- ]
but I would like to "inject" information about user role into response likat that:
- [
- {
- "id": 1,
- "name": "Test project",
- "user_id": 1,
- "created_at": "2018-05-01 01:02:03",
- "updated_at": "2018-05-01 01:02:03",
- "pivot": {
- "user_id": 2,
- "project_id": 17,
- "role_id": 1
- },
- roles: [
- {
- "id": 1,
- "name": "some role name",
- "display_name": "Some role name",
- "description": "Some role name",
- "created_at": "2018-05-01 01:02:03",
- "updated_at": "2018-05-01 01:02:03",
- }
- ]
- },
- ]
Is it possible? Thanks