phplaravellaravel-9eloquent-relationship

how to display only a field of a relationship using API Resources in Laravel?


I am using Laravel Orion and would like to display the environment relationship , I have this controller:

PostsController:

<?php

namespace App\Http\Controllers\API\V1;

use App\Models\User;
use Orion\Http\Controllers\RelationController;

class PostsController extends RelationController
{
    protected $model = User::class;

    protected $relation = 'posts';

    public function filterableBy(): array
    {
        return ['environment.type'];
    }

    public function includes(): array
    {
        return ['user', 'environment'];
    }
}

PostResource

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{ 
    public function toArray($request)
    {
        return parent::toArray($request) + [
            'environment' => new EnvironmentResource($this->whenLoaded('environment'))
        ];
    }
}

App/Models/Post

<?php 
class Post extends Model
{   
    public function environment(): BelongsTo
    {
        return $this->belongsTo(Environment::class);
    }
}

this the response:

{
    "data": [
        {
            "id": "..",
            "title": "..",
            "body": "...",
            ....        
        }
]
}

I want to load the environment information but is not displaying the environment key. What can I do?


Solution

  • If you are using php 8 or above then you can use it's null safety feature like below and it is also n+1 safe.

    'environment' => $this->whenLoaded('environment')?->type
    

    And if you are below then it would be like

    'environment' => $this->whenLoaded('environment') ? $this->environment->type : '';