ModelResource

Queries

Queries

It is often necessary to initially modify all resource queries to the database. You can easily override the QueryBuilder in the resource.

 namespaces
namespace App\MoonShine\Resources;
 
use Illuminate\Contracts\Database\Eloquent\Builder;
use MoonShine\Laravel\Resources\ModelResource;
 
class PostResource extends ModelResource
{
// ...
 
protected function modifyQueryBuilder(Builder $builder): Builder
{
return $builder->where('active', true);
}
}

If you need to completely override the Builder, you can override the resource method newQuery().

Receiving a Record

The modifyItemQueryBuilder() method is used if you need to modify the query for retrieving a record from the database.

 namespaces
namespace App\MoonShine\Resources;
 
use Illuminate\Contracts\Database\Eloquent\Builder;
use MoonShine\Laravel\Resources\ModelResource;
 
class PostResource extends ModelResource
{
// ...
 
protected function modifyItemQueryBuilder(Builder $builder): Builder
{
return $builder->withTrashed();
}
}

If you need to completely override the Builder for retrieving a record, you can override the resource method findItem().

Eager Load

 namespaces
namespace App\MoonShine\Resources;
 
use MoonShine\Laravel\Resources\ModelResource;
 
class PostResource extends ModelResource
{
protected array $with = ['user', 'categories'];
 
// ...
}

The searchQuery() method allows you to override the query when searching for records.

 namespaces
namespace App\MoonShine\Resources;
 
use MoonShine\Laravel\Resources\ModelResource;
 
class PostResource extends ModelResource
{
// ...
 
protected function searchQuery(string $terms): void
{
$this->newQuery()->where(function (Builder $builder) use ($terms): void {
// Your logic
});
}
}

If you only want to expand the query, you need to call the parent method.

 namespaces
namespace App\MoonShine\Resources;
 
use MoonShine\Laravel\Resources\ModelResource;
 
class PostResource extends ModelResource
{
// ...
 
protected function searchQuery(string $terms): void
{
parent::searchQuery($terms);
 
$this->newQuery()->where(function (Builder $builder) use ($terms): void {
// Your logic
});
}
}
 
You can also completely override the logic, including full-text search.
 
```php
protected function resolveSearch(string $terms, ?iterable $fullTextColumns = null): static
{
// Your logic
 
return $this;
}

Sorting

By overriding the resolveOrder() method, you can customize the sorting of records.

 namespaces
namespace App\MoonShine\Resources;
 
use MoonShine\Laravel\Resources\ModelResource;
 
class PostResource extends ModelResource
{
// ...
 
protected function resolveOrder(string $column, string $direction, ?Closure $callback): static
{
if ($callback instanceof Closure) {
$callback($this->newQuery(), $column, $direction);
} else {
$this->newQuery()->orderBy($column, $direction);
}
 
return $this;
}
}