# Custom query behavior

> Implement source-specific sorting and search callbacks.

Source: https://docs.inertiax.dev/table/guide/query-callbacks/

Use `sortUsing()` or `searchUsing()` when the stored field differs from the displayed field. Declare which sources the callback supports.

For complete retrieval from an API or repository, use a [custom source](https://docs.inertiax.dev/table/guide/custom-sources/). The callbacks below operate on Eloquent/collection data and conflict with custom-source execution.

## Sort by another field

```php
use Illuminate\Database\Eloquent\Builder;
use InertiaX\Table\Columns\TextColumn;
use InertiaX\Table\Enums\DataSourceKind;

TextColumn::make('display_name')
    ->sortable()
    ->sortUsing(
        fn (Builder $query, string $direction): Builder =>
            $query->orderBy('last_name', $direction),
        DataSourceKind::Eloquent,
    );
```

## Search a stored field

```php
TextColumn::make('display_name')
    ->searchable()
    ->searchUsing(
        fn (Builder $query, string $term): Builder =>
            $query->where('full_name', 'like', '%'.$term.'%'),
        DataSourceKind::Eloquent,
    );
```

This example uses the database’s `LIKE` behavior. Choose the comparison your application needs. The source must also supply `display_name` for the cell value.

## Callback contract

Sort and search callbacks return the same source kind they receive: an Eloquent builder or a Laravel collection. They cannot return `null`. Clause callbacks have a different contract; see [Clause API](https://docs.inertiax.dev/table/reference/clause/).

Callback parameters can use the available context names: `source` or `query`, `column`, and `direction` for sorting or `term` for search. Here `column` is the Column object, not its key string. Use typed dependencies for services resolved through Laravel’s container.

`supportsSortSources()` and `supportsSearchSources()` can declare supported sources separately. Use `DataSourceKind::Collection` only when the callback also implements collection behavior. Undeclared sources and invalid return types fail with context.

Keep the supplied query’s access constraints intact. See [Custom query security](https://docs.inertiax.dev/table/guide/security/#custom-query-behavior).
