'Resource: Use whenPivotLoaded as condition

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"
  }
}


Solution 1:[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;
            }),
    ];
}

Solution 2:[2]

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),

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Salim
Solution 2 Jovan Djordjevic