Search code examples
laravellaravel-7laravel-resource

How can I create a Laravel Resource relationship for a belongsTo?


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!


Solution

  • Have you tried it with the new keyword?

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