---
title: "Query scopes — Likes for Laravel | Roundly"
description: "Order by like count, filter to what an actor liked or didn’t, and hydrate likes_count — all composable, all typed."
url: https://roundly-consulting.com/open-source/docs/likes-for-laravel/query-scopes
language: en
---

[All packages](https://roundly-consulting.com/open-source.md)

[Likes for Laravel](https://roundly-consulting.com/open-source/docs/likes-for-laravel.md)

# Query scopes

HasLikes adds query scopes for popularity lists and filters:

```php
Post::orderByLikesDesc()->limit(10)->get();  // most-liked first (no N+1)
Post::orderByLikes()->get();                 // least-liked first
Post::whereLikedBy($user)->get();            // posts the user liked
Post::whereNotLikedBy($user)->get();         // posts the user has not liked
Post::withLikesCount()->get();               // hydrate a likes_count attribute
```

Every scope takes an optional reaction type as its last argument and composes with the rest of your query. A typed count lands in its own attribute — likes\_{type}\_count — so it is never mistaken for the all-reactions total:

```php
Post::orderByLikesDesc('love')->limit(10)->get();  // most-loved first
Post::whereLikedBy($user, 'love')->get();          // posts the user loved
Post::withLikesCount('love')->get();               // hydrate likes_love_count

Post::query()
    ->whereNotLikedBy($user)
    ->orderByLikesDesc()
    ->paginate(20);
```

## How the scopes behave

- Without a type, the scopes match any reaction — whereLikedBy($user) finds posts the user reacted to in any way. The instance checks (isLikedBy(), hasLiked()) default to default\_reaction instead.
- orderByLikes() and orderByLikesDesc() hydrate likes\_count (or likes\_{type}\_count for a typed sort) as they sort, so each row carries its count without another query. withLikesCount() and withLikesCount('love') can be combined on one query.
- Soft-deleted (unliked) rows never count.

## Show your open-source love

This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.

[More ways to support, including crypto](https://roundly-consulting.com/support-us.md)

By donating, you agree to our [donation terms](https://roundly-consulting.com/donation-terms.md).

[Support our open source work (opens in a new tab)](https://donate.stripe.com/dRmeVe8FX5PF1Qd9pXcEw00) [Join us on Patreon (opens in a new tab)](https://www.patreon.com/cw/roundly)

## Want this built into your product?

We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.

[Get a quote in 48 hours](https://roundly-consulting.com/contact.md) [Browse all packages](https://roundly-consulting.com/open-source/docs/likes-for-laravel.md)
