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] Support passing default as named parameter in whenLoaded, whenAggregated, whenCounted #51342

Draft
wants to merge 1 commit into
base: 11.x
Choose a base branch
from

Conversation

hn-seoai
Copy link

@hn-seoai hn-seoai commented May 8, 2024

Because of the way named parameters affect func_num_args(), only specifying the required parameters and $default would result in the returned value being null

This will allow developers to use named arguments when passing $default to whenLoaded(), whenAggregated() and whenCounted() in Resources, in case the key should still exist in the output while maintaining the current behavior when only passing the required parameters.

Before:

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'author' => new AuthorResource($this->whenLoaded('author', fn ($author) => $author, null)),
        ];
    }
}

After:

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'author' => new AuthorResource($this->whenLoaded('author', default: null)),
        ];
    }
}

This will not affect existing Laravel users, as the addition is only being run when $value and/or $default is passed and $value is its default (null).

@taylorotwell
Copy link
Member

Can you explain how this works?

@hn-seoai
Copy link
Author

Can you explain how this works?

Providing whenLoaded with only the relationship and default parameters will result in func_num_args() returning 3, which makes the default null value of the value parameter persist instead of using the default behavior when only providing the relationship.

value(...) returns the value() method as a closure with the same signature, so the final return statement will return $loadedValue instead of null.

@taylorotwell
Copy link
Member

Can you add a test for this?

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.

None yet

2 participants