0

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"
  }
}
Salim Djerbouh
  • 10,719
  • 6
  • 29
  • 61
SPQRInc
  • 162
  • 4
  • 23
  • 64

2 Answers2

1

Since the pivot is either loaded or not, just negate the entire expression for another field, it'll never be duplicated

public function toArray($request)
{

    return [
        'id'     => $this->id,
        'title'  => $this->whenPivotLoaded('item_groups_attribute',
            function () {
                return $this->pivot->title . "Hello";
            }),
        'title'  => !$this->whenPivotLoaded('item_groups_attribute',
            function () {
                return $this->title;
            }),
    ];
}
Salim Djerbouh
  • 10,719
  • 6
  • 29
  • 61
  • This should work. But `this->whenPivotLoaded` returns `\Illuminate\Http\Resources\MissingValue` if there's no pivot, so I'd have to check using `instanceof` – SPQRInc Oct 05 '19 at 11:53
0

Very late answer but $this-whenPivotLoaded() accepts default value as a third parameter

In your case it would be something like:

$this->whenPivotLoaded('item_groups_attribute', function () {
                return $this->pivot->title . "Hello";
            }, $this->title),