AthenaeumAthenaeum
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
  • Version 6.x

    • Release Notes
    • Upgrade Guide
    • New to this...
    • Contribution Guide
    • Security Policy
    • Code of Conduct
    • Origin
  • ACL

    • Introduction
    • How to install
    • Setup
    • Permissions
    • Roles
    • Users
    • Cached Permissions
  • Audit

    • Audit
    • How to install
    • Setup
    • Recording
    • Events
  • Circuits

    • Circuits
    • How to install
    • Setup
    • Usage
    • Events
  • Collections

    • Collections
    • How to install
    • Summation

      • Summation Collection
      • Items Processor
  • Config

    • Configuration Loader
    • How to install
    • Setup
    • Load Configuration Files
    • Custom File Parsers
  • Console

    • Command and Schedule Registration
    • How to install
    • Setup
    • Commands
    • Schedules
  • Container

    • IoC Service Container
    • How to install
    • Container
    • List Resolver
  • Core

    • Athenaeum Core Application
    • How to install
    • Setup
    • Usage

      • Configuration
      • Service Providers
      • Service Container
      • Events
      • Caching
      • Logging
      • Console
      • Task Scheduling
      • Exception Handling
      • Extending Core Application
      • Testing
  • Database

    • Introduction
    • How to install
    • Models

      • Instantiatable
      • Sluggable
    • Query

      • Criteria (Query Filter)
  • Dto

    • Data Transfer Object (DTO)
    • How to install
    • Create Interface
    • Implement DTO
    • How to use
    • Populate
    • Export
    • Json
    • Serialization
    • Nested DTOs
    • Array DTO
  • ETags

    • ETags
    • How to install
    • Setup
    • Usage
    • Generators

      • Default Generator
      • Custom Generator
    • Eloquent Models
    • Macros
  • Events

    • Register Listeners and Subscribers
    • How to install
    • Setup
    • Listeners
    • Subscribers
  • Filters

    • Search Filter Utilities
    • Prerequisites
    • How to install
    • Setup
    • Processor
    • Filters Builder
    • Predefined Resources

      • Search Processor
      • Sorting Processor
      • Constraints Processor
      • Matching Processor
    • Tip: Create a base builder
  • Flysystem

    • Introduction
    • Database Adapter

      • Introduction
      • How to install
      • Setup
      • Data Deduplication
      • MIME-Type Detection
  • Http

    • Api

      • Http API
      • How to install
      • Setup
      • Resources

        • Introduction
        • Timestamps
        • Self-Link
        • Relations
        • Registrar
      • Middleware

        • Introduction
        • Request Must Be Json
        • Capture Fields To Select
    • Clients

      • Http Clients
      • How to install
      • Setup
      • Basic Usage
      • Available Methods

        • Fluent Api
        • Protocol Version
        • Base Uri
        • Http Method and Uri
        • Headers
        • Accept & Content-Type
        • Authentication
        • Http Query
        • Payload Format
        • Payload
        • Attachments
        • Cookies
        • Response Expectations
        • Middleware
        • Conditions
        • Criteria
        • Redirects
        • Timeout
        • Debugging
        • Logging
        • Driver Options
        • Driver
      • Http Query Builder

        • Introduction
        • Select
        • Where
        • Dates
        • Include
        • Pagination
        • Sorting
        • Raw Expressions
        • Custom Grammar
    • Cookies

      • Http Cookies
      • How to install
      • Usage
    • Messages

      • Http Messages
      • How to install
      • Serializers
  • Maintenance

    • Modes

      • Maintenance Modes
      • How to install
      • Setup
      • Basic Usage
      • Available Drivers
  • Mime Types

    • MIME-Types
    • How to install
    • Setup
    • Usage
    • Drivers

      • Available Drivers
      • File Info
  • Properties

    • Properties Overload
    • How to install
    • Usage
    • Naming Convention
    • Properties Visibility
  • Redmine

    • Redmine Api Client
    • How to install
    • Setup
    • General Usage

      • Supported Operations
      • Fetch list of resources
      • Find
      • Fetch
      • Create new record
      • Update existing record
      • Delete existing record
      • Relations
    • Available Resources

      • Predefined Resources
      • Attachments
      • Enumerations
      • Issue Relations
      • Users
      • User Groups
      • Roles
      • Project Memberships
      • Versions (Milestones)
      • Issue Categories
      • Trackers
  • Service

    • Service Registrar
    • How to install
    • How to use
  • Streams

    • Streams
    • How to install
    • Setup
    • How to use

      • Introduction
      • Open and Close
      • Raw Resource
      • Seeking
      • Reading
      • Writing
      • Size
      • Truncate
      • Flush
      • Hash
      • MIME-Type
      • Output
      • Locking
      • Transactions
      • Meta
      • Misc
  • Support

    • Introduction
    • How to install
    • Laravel Aware-of Helpers

      • How to use
      • Enforce Via Interface
      • Custom Default
      • Pros and Cons
      • Available Helpers
    • Aware-of Properties

      • Generator
      • Available Aware-of Helpers
    • Live Templates
  • Testing

    • Introduction
    • How to install
    • Test Cases
    • Testing Aware-of Helpers
  • Utils

    • Introduction
    • How to install
    • Array
    • Duration
    • Json
    • Math
    • Memory
    • Method Helper
    • Invoker
    • Populatable
    • String
    • Version
  • Validation

    • Introduction
    • How to install
    • Setup
    • Rules

      • Alpha-Dash-Dot
      • Semantic Version
You are viewing documentation for an outdated version. It is no longer supported!

Criteria (Query Filter)

A way to encapsulate custom queries for your Eloquent models. These can be used as an alternative or complementary to Laravel's query scopes.

  • How to create a new filter
  • How to use
    • Apply Multiple Filters
  • Applicability
  • Field Criteria (Field Filter)

How to create a new filter

Extend the Filter abstraction and implement the apply() method.

use Aedart\Database\Query\Filter;
use Illuminate\Contracts\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Contracts\Database\Query\Builder;

class VideoGamesCategoryFilter extends Filter
{
    public function apply(Builder|EloquentBuilder $query)
    {
        return $query->where('name', '=', 'Video Games');
    }
}

How to use

Once you have your filter created, you can apply it in your Eloquent model. Use the Filtering trait and call the applyFilters() method.

In your model

use Illuminate\Database\Eloquent\Model;
use Aedart\Database\Models\Concerns\Filtering;

class Category extends Model
{
    use Filtering;
}

Apply filter

$result = Category::applyFilters(new VideoGamesCategoryFilter())->first();

Apply Multiple Filters

The applyFilters() accepts either a single filter instance or a list of filters.

$result = Category::applyFilters([
    new OldRecords(),
    new HasDiscounts(),
    new NotDeleted()
])->get()

Applicability

Each filter has a isApplicable() method. It is used to determine whether the filter must be applied or not. By default, this method will always return true. However, if you need to exclude a filter, then you should overwrite this method.

Two parameters are provided:

  • $query: The current query scope.
  • $filters: List of all the filters that are about to be applied.

These parameters can be used for your determination logic, if it makes sense for you. Otherwise, simply ignore them.

use Aedart\Database\Query\Filter;
use Acme\Filters\IsDeleted;
use Illuminate\Contracts\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Contracts\Database\Query\Builder;

class OldRecords extends Filter
{
    public function isApplicable(Builder|EloquentBuilder|null $query = null, $filters = []): bool
    {
        // Prevent this filter, if another specific filter is about
        // to be applied...
        foreach($filters as $filter) {
            if ($filter instanceof IsDeleted) {
                return false;
            }
        }
        
        return true;
    }

    // ... remaining not shown ... //
}

Whenever the above shown filter is used, in combination with a IsDeleted filter, it will be ignored and not applied.

$result = Category::applyFilters([
    new OldRecords(), // Will be ignored
    new IsDeleted()
])->get()

Field Criteria (Field Filter)

If you require filters that add where <expression> constraints for a single field (column) on your query, then you can choose to inherit from the FieldFilter. This abstraction allows you to create slightly more constraints to be applied using either AND or OR logical operator.

use Aedart\Database\Query\FieldFilter;
use Aedart\Contracts\Database\Query\FieldCriteria;
use Illuminate\Contracts\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Contracts\Database\Query\Builder;

class StringFilter extends FieldFilter
{
    public function apply(Builder|EloquentBuilder $query)
    {
        if ($this->logical() === FieldCriteria::OR) {
            return $query->orWhere($this->field(), $this->operator(), $this->value());
        }

        return $query->where($this->field(), $this->operator(), $this->value());
    }
}

Usage

use Aedart\Contracts\Database\Query\FieldCriteria;

$result = Category::applyFilters([
    StringFilter::make('name', 'LIKE', '%games%', FieldCriteria::OR),
    StringFilter::make('name', 'LIKE', '%video%', FieldCriteria::OR),
])->get()

How you choose to design your "field" specific filters, is left to your imagination. For additional information, please review the source code.

Edit page
Last Updated: 16/02/2023, 09:10
Contributors: alin, Alin Eugen Deac