I would like to have this:
- A collection returns
'title' => $this->title
when it's loaded without a pivot - A collection returns
title => $this->pivot->title . "Hello World"
when it's loaded with pivot.
This is my approach:
namespace App\Http\Resources;
use App\Item;
use Illuminate\Http\Resources\Json\JsonResource;
class ItemResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
*
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->whenPivotLoaded('item_groups_attribute',
function () {
return $this->pivot->title . "Hello";
}), // but how to add $this->title, if it's not with pivot?
];
}
}
If I try something like this:
'title' => $this->whenPivotLoaded('item_groups_attribute',
function () {
return $this->pivot->title . "Hello";
}) ?: $this->title,
this does not work, as the result is
no pivot (the title does not appear in fields):
{
"data": {
"id": 2
}
}
This is the response if loaded with pivot:
{
"data": {
"id": 5,
"title": "Test"
}
}