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

[9.x] Add whenNotNull method #41769

Merged

Conversation

smokills
Copy link
Contributor

This PR adds a new whenSelectedMethod to the ConditionallyLoadsAttributes trait. This is basically a syntactic sugar around the when method. Working with the spatie query builder, I found that I was iterating the same checks for every resource, so maybe this little wrapper could be helpful to maintain the logic inside the Resource as clean as possible.

@smokills
Copy link
Contributor Author

smokills commented Apr 1, 2022

Another thing that I realized during the development, is that maybe could be handy to include the Macroable trait in the JsonResource class. In this way, developers could make packages in order to easily extend them. In my case I create another JsonResource base class, that extends the original one, with the trait included, so I was able to reuse the method above through all my Resources:

JsonResource::macro('whenSelected', function ($column, $default = null) {
    $args = func_num_args() == 1 ?
        [$column] :
        [$column, $default];

    return $this->when(!is_null($column), ...$args);
});

@taylorotwell
Copy link
Member

Should it be a bit more explicitly named? Like just whenNotNull?

@smokills
Copy link
Contributor Author

smokills commented Apr 1, 2022

Sure thing! I'll do it right now. What about the Macroble trait? I think that the community would benefit from that.

@GrahamCampbell GrahamCampbell changed the title feat: add whenSelected method [9.x] Add whenSelected method Apr 1, 2022
@smokills smokills changed the title [9.x] Add whenSelected method [9.x] Add whenNotNull method Apr 1, 2022
@taylorotwell
Copy link
Member

JsonResource is already macroable via the DelegatesToResource trait (which uses Macroable).

@taylorotwell taylorotwell merged commit a466fb0 into laravel:9.x Apr 1, 2022
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