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

Merged
merged 1 commit into from
Aug 1, 2024

Conversation

hn-seoai
Copy link
Contributor

@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
Contributor 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?

@driesvints driesvints marked this pull request as ready for review July 26, 2024 08:28
@driesvints
Copy link
Member

@hn-seoai don't forget to mark a PR as ready so Taylor can review it.

@taylorotwell taylorotwell merged commit c417c6a into laravel:11.x Aug 1, 2024
28 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.

3 participants