[email protected]
4 months ago

Issue with Eloquent: API Resources - Conditional Relationships

Posted 4 months ago by [email protected]

I think I might have found a bug in Laravel, please see the below code:

I am hitting an endpoint which is /api/users/1

public function show(User $user)
{
    return new UserResource($user);
}

My Resource looks like the below:

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request)
    {

        //dd($this);

        return [
            'uuid'               => $this->uuid,
            'name'               => $this->name,
            'currency'           => $this->currency,
            'company'            => new CompanyResource($this->whenLoaded('company')),
            'created_at'         => $this->created_at,
            'updated_at'         => $this->updated_at,
        ];
    }
}

Now I would expect the company property not to return in the JSON however it does, can anyone see a reason why the company relation is being loaded and added to the JSON response when I am not using ->with() anywhere in my code?

Sorry if this is a total n00b mistake but I want to properly understand the new API resource stuff in Laravel and I feel like I am making a mistake.

Please sign in or create an account to participate in this conversation.