Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Add whenExistsLoaded method to conditionally include relationship existence attribute #52295

Merged
merged 5 commits into from
Aug 1, 2024

Conversation

CodeWithKyrian
Copy link
Contributor

Introduction

This PR introduces a new method, whenExistsLoaded, to the Illuminate\Http\Resources\ConditionallyLoadsAttributes trait. This method allows developers to conditionally include a relation existence attribute in their API resources if it was eager loaded.

Background

Laravel's JsonResource currently provides several methods to conditionally include data in API responses based on whether certain relationships or attributes have been loaded. These methods include:

  • whenLoaded: to include a relationship if it was eager loaded.
  • whenCounted: to include a relationship count if it was eager loaded.
  • whenAggregated: to include an aggregated value if it was eager loaded.

However, there is currently no method for conditionally including a relation existence attribute that has been eager loaded. This feature addresses that gap, providing a consistent API for conditional inclusion of various types of data.

Usage

Here is an example of how this new method can be used:

public function toArray(Request $request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'relation_exists' => $this->whenExistsLoaded('relation'),
    ];
}

@CodeWithKyrian CodeWithKyrian changed the title feat: add whenExistsLoaded method to conditionally include relationship existence attribute [11.x] Add whenExistsLoaded method to conditionally include relationship existence attribute Jul 27, 2024
@taylorotwell
Copy link
Member

Please remove all of the white space related changes.

@taylorotwell taylorotwell marked this pull request as draft July 29, 2024 07:40
@CodeWithKyrian CodeWithKyrian marked this pull request as ready for review July 29, 2024 09:21
@taylorotwell taylorotwell merged commit edc106e into laravel:11.x Aug 1, 2024
29 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants