Skip to content

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?

@taylorotwell taylorotwell marked this pull request as draft May 10, 2024 19:40
@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.

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