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?