Skip to content

[9.x] Add whenNotNull method#41769

Merged
taylorotwell merged 6 commits into
laravel:9.xfrom
smokills:feature/eloquent-resource-when-selected
Apr 1, 2022
Merged

[9.x] Add whenNotNull method#41769
taylorotwell merged 6 commits into
laravel:9.xfrom
smokills:feature/eloquent-resource-when-selected

Conversation

@smokills

Copy link
Copy Markdown
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

smokills commented Apr 1, 2022

Copy link
Copy Markdown
Contributor Author

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
Copy Markdown
Member

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

@smokills

smokills commented Apr 1, 2022

Copy link
Copy Markdown
Contributor Author

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
Copy Markdown
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