0

My DB scheme among others includes the pivot table:

user_workshop
- id
- user_id
- workshop_id
- accepted_at
- rejected_at
// other fields...

with the respective models User & Workshop and the belongsToMany relationships in each.

Trying to access those in a nested resource manner:

Route::apiResource('users', 'UserController');
Route::apiResource('users.workshops', 'WorkshopController');

works fine but if I add a field ( in the toArray method ) to be added only if the pivot is loaded, then that field is never added in the response.

E.g. consider the following WorkshopResource resource:

class Workshop extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            // other fields ...
            'conditional_field' => $this->whenPivotLoaded('user_workshop', function() {
                return 'works';
            }),
        ];
    }
}

The conditional_field is not added for example in the following request:

https://<tld>/api/users/1/workshops

whereas rest fields are there.

Any help with that?

achariso
  • 1
  • 1
  • 1

0 Answers0