0

I got a resource that comes with two possible pivots. Now I'd like to add values depending on which pivot is loaded.

This is how I am doing it at the moment:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\PotentiallyMissing;


class CarAttributeResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'         => $this->id,
            'title'      => ($title
                = $this->whenPivotLoaded('car_car_attribute',
                function () {
                    return (boolean)$this->pivot->custom === true
                        ? $this->pivot->title : $this->title;
                })) instanceof PotentiallyMissing
            && $title->isMissing() ? (($title_ppa
                = $this->whenPivotLoaded('car_bundle_car_bundle_attribute',
                function () {
                    return (boolean)$this->pivot->custom === true
                        ? $this->pivot->title : $this->title;
                })) instanceof PotentiallyMissing
            && $title_ppa->isMissing() ? $this->title : $title_ppa) : $title,
        ];
    }
}

Does not look nice at all, right?

Do you guys see any possibilities to make this more elegant and readable?

SPQRInc
  • 162
  • 4
  • 23
  • 64
  • 2
    Move this code to model – Styx Oct 16 '19 at 09:32
  • The model itself can not determine, whether it's loaded with pivot or not, or am I wrong? – SPQRInc Oct 16 '19 at 09:46
  • 2
    Of course it can. When you're using `$this` in resource it actually proxies these calls to the underlying model object. – Styx Oct 16 '19 at 09:49
  • Alright. So if I would edit my model's attribute via an accessor, I could check, if there's a pivot table loaded? Could you link me the docs for this? – SPQRInc Oct 16 '19 at 12:37
  • 1
    You just use `$this->pivot` and `$this->pivot->getTable()` to check whether pivot is loaded or not. – Styx Oct 16 '19 at 16:24
  • Thanks, the `getTable()` method is doing what I want here :-) – SPQRInc Oct 16 '19 at 16:49

0 Answers0