# Search

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

In Forest Admin, pages that show lists of records have a free-text search bar on top of them.

![A search bar on the main Table View](https://647272774-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FABtuALf2WDQ7fxhI0JPa%2Fuploads%2Fgit-blob-00fa94649d3216d7ad00c01b3d8f265640a18bbc%2Fsearch-bar.png?alt=media)

### Search modes

2 search modes are supported: "normal" and "extended".

* All searches start by being a "normal" search.
* If the records users are looking for are not found, it is possible to trigger an "extended" search from the footer.

![Extended search call to action](https://647272774-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FABtuALf2WDQ7fxhI0JPa%2Fuploads%2Fgit-blob-b9f623ed66153f599f370a71ec8aeef31d50e21b%2Fsearch-bar-extended.png?alt=media)

### Default behavior

Natively, the search behavior is to seek value occurrences within columns of the Collection (in normal mode), and columns of the Collections of direct relations (in extended mode).

By default, Forest Admin will search only in specific columns, depending on their type:

| Column Type | Default search behavior                                                 |
| ----------- | ----------------------------------------------------------------------- |
| Enum        | Column is equal to the search string (case-insensitive).                |
| Number      | Column is equal to the search string (if the search string is numeric). |
| String      | Column contains the search string (case-insensitive).                   |
| Uuid        | Column is equal to the search string.                                   |
| Other types | Column is ignored by the default search handler.                        |

### Customization

If you want to make a column searchable, you must define the right operator to allow the search to be performed. Please refer to the [Operators to support](https://docs.forestadmin.com/developer-guide-agents-php/fields/filter#operators-to-support-to-enable-the-search) table to know which operator to define.

Alternatively, you may want to change how the search behaves in your admin panel.

For instance:

* search only on the columns that are relevant to your use case.
* use full-text indexes (i.e. Postgres `tsquery` and `tsvector`, Algolia, Elastic search, ...)

To customize the search behavior, you must define a handler that returns a [`ConditionTree`](https://docs.forestadmin.com/developer-guide-agents-php/data-sources/getting-started/queries/filters#condition-trees).

#### Making the search case-sensitive by default

In this example, we use the `searchExtended` condition to toggle between case-sensitive and insensitive searches.

```php
use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;

$forestAgent->customizeCollection(
    'People',
    function (CollectionCustomizer $builder) {
        $builder->replaceSearch(
            function ($searchString, $extendedMode) {
           	    $operator = $extendedMode ? Operators::CONTAINS : Operators::ICONTAINS;

                return [
                	'aggregator' => 'Or',
                	'conditions' => [
                	    ['field' => 'firstName', 'operator' => $operator, 'value' => $searchString],
                	    ['field' => 'lastName', 'operator' => $operator, 'value' => $searchString],
                	]
                ];
            }
        );
    }
);
```

#### Changing searched columns

```php
use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;

$forestAgent->customizeCollection(
    'Product',
    function (CollectionCustomizer $builder) {
        $builder->replaceSearch(
            function ($searchString, $extendedMode) {
                $productReferenceRegexp = '/^[a-f]{16}$/i';
                $barCodeRegexp = '/^[0-9]{10}$/i';

           	    // User is searching using a product reference.
           	    if (preg_match($productReferenceRegexp, $str)) {
           	        return ['field' => 'reference', 'operator' => Operators::EQUAL, 'value' => $searchString];
           	    }

           	    // User is search a barcode
           	    if (preg_match($barCodeRegexp, $str)) {
           	        return ['field' => 'barCode', 'operator' => Operators::EQUAL, 'value' => $searchString];
           	    }

           	    // User is searching something else, in "normal" mode, let's search in the product name only
           	    if (! $extendedMode) {
           	        return ['field' => 'name', 'operator' => Operators::CONTAINS, 'value' => $searchString];
           	    }

           	    // In "extended" mode, we search on name, description and brand name
                return [
                	'aggregator' => 'Or',
                	'conditions' => [
                	    ['field' => 'name', 'operator' => Operators::CONTAINS, 'value' => $searchString],
                	    ['field' => 'description', 'operator' => Operators::CONTAINS, 'value' => $searchString],
                	    ['field' => 'brand:name', 'operator' => Operators::EQUAL, 'value' => $searchString],
                	]
                ];
            }
        );
    }
);
```

#### Calling an external API

If your data is indexed using a SaaS, an external store, or a full-text index, you can call it in the search handler.

```php
use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;
use Algolia\AlgoliaSearch\SearchClient;

$forestAgent->customizeCollection(
    'Product',
    function (CollectionCustomizer $builder) {
        $builder->replaceSearch(
            function ($searchString, $extendedMode) {
                $client = SearchClient::create("YourApplicationID", "YourWriteAPIKey");
                $index = $client->initIndex("test_index");
                $results = $index->search(
                    $searchString,
                    [
                        'attributesToRetrieve' => ['id'],
                        'hitsPerPage' => 50,
                    ]
                );

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

#### Disable the search

By default, the search bar is displayed when at least one field supports the operator used for search based on its type ([see this table](#default-behavior)).

You can remove the search bar by disabling the search on a collection:

```php
use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;

$forestAgent->customizeCollection(
    'Product',
    function (CollectionCustomizer $builder) {
        $builder->disableSearch();
    }
);
```
