2

I have created a UserResource that is successfully returning all of my user attributes, including the organization it belongs to. It looks something like this:

Resources/User.php

return [
    'type' => 'users',
    'id' => (string)$this->id,
    'attributes' => [
        'name' => $this->name,
        'email' => $this->email,
        ...
        'relationships' => [
            'organization' => $this->organization,
        ],
    ];

In my User model, there is a belongsTo relationship for User->Organization.

Instead of returning the actual organization model, I'd like to return the organization resource.

For example, an organization hasMany locations:

Resources/Organization.php

return [
    'type' => 'organizations',
    'id' => (string)$this->id,
    'attributes' => [
        'name' => $this->name,
        ...   
        'relationships' => [
            'locations' => Location::collection($this->locations),
        ],
    ];

I can successfully return the collection of locations that belong to the organization. I have not been able to return a belongsTo relationship.

I've tried:

Resources/User.php

'relationships' => [
    'organization' => Organization::collection($this->organization),
],

// or this
'relationships' => [
    'organization' => Organization::class($this->organization),
],

// or this
use App\Http\Resources\Organization as OrganizationResource;
...

'relationships' => [
    'organization' => OrganizationResource($this->organization),
],

How can I return a single model as a related resource? Thank you for any suggestions!

Damon
  • 4,151
  • 13
  • 52
  • 108

1 Answers1

3

Have you tried it with the new keyword?

'relationships' => [
    'organization' => new OrganizationResource($this->organization),
],
Dan
  • 5,140
  • 2
  • 15
  • 30
  • That was it - thank you! Out of my own naïveté, why do I need to use `new` for returning a `belongsTo`, but can simply just use the `::collection` to return a `hasMany`? – Damon May 30 '20 at 15:47