# Segments

{% hint style="success" %}
This is the official documentation of the `forestadmin/laravel-forestadmin` v2+ and `forestadmin/symfony-forestadmin` PHP agents.
{% endhint %}

A Segment is a subset of a Collection: it's a saved filter of your Collection.

Segments are designed for those who want to *systematically* visualize data according to specific sets of filters. It allows you to save filter configurations so user don’t have to do repetitive actions every day.

![](https://647272774-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FABtuALf2WDQ7fxhI0JPa%2Fuploads%2Fgit-blob-b91265b079fd224c5918e2e8fabdee9d1f92d6c4%2Fsegment-example.png?alt=media)

## From your admin panel

Segments can be configured from the interface, without the need to write any code.

This is documented in the [User Guide](https://docs.forestadmin.com/user-guide/collections/segments).

## From your Agent

Sometimes, Segment filters are complicated and closely tied to your business. Forest Admin allows you to code how the Segment is computed.

For instance, in our [Live Demo example](https://app.forestadmin.com/livedemo), we’ve implemented a Segment on the collection `products` to allow admin users to see the bestsellers at a glance.

### Example

{% hint style="info" %}
In the following example, we are making queries using the [Forest Admin Query Interface](https://docs.forestadmin.com/developer-guide-agents-php/data-sources/getting-started).

As Forest Admin does not impose any restriction on the handler, you are free to call external APIs or query your database directly instead.
{% endhint %}

The only requirement when implementing a Segment from your agent is to return a valid `ConditionTree` (see [Understanding Filters](https://docs.forestadmin.com/developer-guide-agents-php/data-sources/getting-started/queries/filters)).

```php
use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceCustomizer\Context\CollectionCustomizationContext;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Aggregation;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Filters\Filter;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;

$forestAgent->customizeCollection(
    'Customer',
    function (CollectionCustomizer $builder) {
        $builder->addSegment(
            'mostPurchased',
            function (CollectionCustomizationContext $context) {
                $rows = $context->getDatasource()->getCollection('Order')->aggregate(
                    new Filter(),
                    new Aggregation(operation: 'Count', groups: [['field' => 'category_id']]),
                    10
                );

                return [
                    'field'    => 'id',
                    'operator' => Operators::IN,
                    'value'    => array_map(fn ($r) => $r['product_id'], $rows)
                ];
            }
        );
    }
);
```
