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 whenCounted to JsonResource #43101

Merged
merged 7 commits into from
Jul 14, 2022
Merged

[9.x] Add whenCounted to JsonResource #43101

merged 7 commits into from
Jul 14, 2022

Conversation

stevebauman
Copy link
Contributor

@stevebauman stevebauman commented Jul 8, 2022

Description

This PR adds a whenCounted method to the JSON resource class giving us the ability to conditionally include attributes in a response when a relation count is set on the model via Post::withCount('comments').

This method acts nearly identically to whenLoaded, with the exception that the retrieved count attribute value will be passed into the $value callback (if one is provided).

I've also added a hasAttribute method to models to easily determine if an attribute exists inside of the models raw $attributes array, so I didn't have to fetch all of the models attributes to determine if it exists:

if (! isset($this->resource->getAttributes()[$attribute])) {
    // ...
}

Example

class PostController
{
    public function show(Post $post)
    {
        return new PostResource($post->loadCount('comments'));
    }
}
class PostResource extends PostResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'comments_count' => $this->whenCounted('comments'),
        ];
    }
}

Important

If you'd prefer not having the hasAttribute method added onto Eloquent models, let me know and I can remove it!

Thanks for your time! ❤️

@taylorotwell
Copy link
Member

@stevebauman yeah, you can remove that hasAttribute method from Eloquent.

@taylorotwell taylorotwell marked this pull request as draft July 13, 2022 13:13
@stevebauman stevebauman marked this pull request as ready for review July 13, 2022 14:22
@taylorotwell taylorotwell merged commit 1b09251 into laravel:9.x Jul 14, 2022
@taylorotwell
Copy link
Member

Can you PR docs for this @stevebauman ?

@stevebauman
Copy link
Contributor Author

Sure thing @taylorotwell 👍

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