I'm trying to use Laravel's API Resources to handle some JSON and I'm not able to conditionally load a relationship, despite it being eager loaded.
My controller:
$games = Game::with('availableInterests')->get();
In my view, I'm json encoding the collection to be used in VueJS
games = @json(new \App\Http\Resources\GameCollection($games)),
GameCollection - unchanged from the class Laravel generated for me.
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class GameCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
GameResource
class GameResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'thumbnail_url' => $this->thumbnail_url,
'available_interests' => Interest::collection($this->whenLoaded('availableInterests')),
];
}
}
Game Model's Relationship
public function availableInterests() : BelongsToMany
{
return $this->belongsToMany(Interest::class);
}
I've tried changing $this->whenLoaded('availableInterests') to $this->whenLoaded('available_interests') with no luck. I've double checked my spelling with no luck.
Why isn't this conditional relationship present in the json?
Even removing $this->whenLoaded() doesn't make this relationship appear.
with()to eager load the relationshipInterest? What works for me in my API app is'reviews' => ReviewResource::collection($this->whenLoaded('reviews')).$with = ['availableInterests'];