# Dynamic Filters Trait - Usage Guide

This guide explains how to use the `HasDynamicFilters` trait for flexible query filtering in your models and services.

## Overview

The `HasDynamicFilters` trait provides powerful dynamic filtering capabilities for Eloquent models. It supports:
- **Search** across multiple fields
- **Field filters** with various operators (equals, like, greater than, etc.)
- **Relationship filters** (filter by related model attributes)
- **Date range filters**
- **Sorting**
- **Automatic validation** of filterable fields

## Installation

The trait is already available at `app/Traits/HasDynamicFilters.php`. Just use it in your models.

## Basic Setup

### 1. Add Trait to Model

```php
<?php

namespace App\Models;

use App\Traits\HasDynamicFilters;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasDynamicFilters;

    // Optional: Define filterable fields (whitelist)
    protected $filterable = [
        'name',
        'sku',
        'price',
        'status',
        'created_at',
    ];

    // Optional: Define searchable fields
    protected $searchable = [
        'name',
        'sku',
        'description',
    ];

    // Optional: Define relationship filters
    protected $relationshipFilters = [
        'category' => 'category.name',
        'brand' => 'brand.name',
        'tag' => 'tags.name',
    ];
}
```

### 2. Use in Service

```php
<?php

namespace App\Services;

use App\Models\Product;

class ProductService
{
    public function getAllProducts(array $params = [])
    {
        $query = Product::with(['category', 'brand']);

        // Apply all dynamic filters
        $query = $query->applyFilters($params);

        // Paginate
        $perPage = $params['per_page'] ?? $params['perPage'] ?? 15;
        return $query->paginate($perPage);
    }
}
```

## Filter Parameters

### Search

Search across all searchable fields:

```
GET /api/products?search=laptop
```

### Field Filters

Filter by specific fields with operators:

#### Basic Equals (default)
```
GET /api/products?status=active
GET /api/products?name=Product Name
```

#### Operators

You can use operators by appending them to the field name:

| Operator | Suffix | Example | Description |
|----------|--------|---------|-------------|
| Equals | `_eq` | `status_eq=active` | Exact match (default) |
| Not Equals | `_ne` | `status_ne=inactive` | Not equal |
| Greater Than | `_gt` | `price_gt=100` | Greater than |
| Greater Than or Equal | `_gte` | `price_gte=100` | Greater than or equal |
| Less Than | `_lt` | `price_lt=1000` | Less than |
| Less Than or Equal | `_lte` | `price_lte=1000` | Less than or equal |
| Like (Contains) | `_like` | `name_like=laptop` | Contains text |
| Not Like | `_not_like` | `name_not_like=test` | Does not contain |
| Starts With | `_starts_with` | `name_starts_with=Pro` | Starts with text |
| Ends With | `_ends_with` | `name_ends_with=2024` | Ends with text |
| In | `_in` | `status_in=active,pending` | Value in list |
| Not In | `_not_in` | `status_not_in=deleted` | Value not in list |
| Is Null | `_is_null` | `deleted_at_is_null=1` | Field is null |
| Is Not Null | `_is_not_null` | `deleted_at_is_not_null=1` | Field is not null |
| Between | `_between` | `price_between=100,500` | Between two values |
| Not Between | `_not_between` | `price_not_between=100,500` | Not between |

**Examples:**
```
GET /api/products?price_gte=100&price_lte=1000
GET /api/products?name_like=laptop
GET /api/products?status_in=active,pending,review
GET /api/products?deleted_at_is_null=1
```

### Relationship Filters

Filter by related model attributes:

```
GET /api/products?category=electronics
GET /api/products?brand=apple
GET /api/products?tag=featured
```

**Multiple values:**
```
GET /api/products?tag[]=featured&tag[]=new
```

### Date Range Filters

Filter by date ranges:

```
GET /api/products?date_from=2024-01-01&date_to=2024-12-31
GET /api/products?date_from=2024-01-01&date_to=2024-12-31&date_field=created_at
```

**Parameters:**
- `date_from` or `dateFrom` - Start date
- `date_to` or `dateTo` - End date
- `date_field` or `dateField` - Field to filter (default: `created_at`)

### Sorting

Sort results:

```
GET /api/products?sort_by=name&sort_order=asc
GET /api/products?sortBy=price&sortOrder=desc
```

**Parameters:**
- `sort_by` or `sortBy` - Field to sort by
- `sort_order` or `sortOrder` - Sort direction (`asc` or `desc`, default: `asc`)

**Relationship sorting:**
```
GET /api/products?sort_by=category.name&sort_order=asc
```

### Pagination

```
GET /api/products?per_page=20&page=2
GET /api/products?perPage=20&page=2
```

## Complete Examples

### Example 1: Basic Filtering

```php
// Model
class Product extends Model
{
    use HasDynamicFilters;

    protected $filterable = ['name', 'sku', 'price', 'status'];
    protected $searchable = ['name', 'sku', 'description'];
}

// Service
public function getAllProducts(array $params = [])
{
    $query = Product::with('category');
    $query = $query->applyFilters($params);
    return $query->paginate($params['per_page'] ?? 15);
}

// API Request
GET /api/products?search=laptop&status=active&price_gte=100&price_lte=1000&sort_by=price&sort_order=desc
```

### Example 2: With Relationship Filters

```php
// Model
class User extends Model
{
    use HasDynamicFilters;

    protected $filterable = ['name', 'email', 'created_at'];
    protected $searchable = ['name', 'email'];
    protected $relationshipFilters = [
        'role' => 'roles.name',
        'permission' => 'permissions.name',
    ];
}

// Service
public function getAllUsers(array $params = [])
{
    $query = User::with('roles');
    $query = $query->applyFilters($params);
    return $query->paginate($params['per_page'] ?? 15);
}

// API Request
GET /api/users?search=john&role=admin&created_at_gte=2024-01-01
```

### Example 3: Complex Filtering

```php
// API Request
GET /api/products?
    search=laptop&
    status_in=active,pending&
    price_gte=100&
    price_lte=2000&
    category=electronics&
    brand=apple&
    date_from=2024-01-01&
    date_to=2024-12-31&
    sort_by=price&
    sort_order=desc&
    per_page=20&
    page=1
```

## Model Configuration

### Filterable Fields

Define which fields can be filtered (whitelist approach):

```php
protected $filterable = [
    'name',
    'email',
    'status',
    'price',
    'created_at',
];
```

**Note:** If `$filterable` is empty or not defined, all table columns can be filtered (less secure).

### Searchable Fields

Define which fields are searched when using the `search` parameter:

```php
protected $searchable = [
    'name',
    'email',
    'description',
];
```

**Relationship search:**
```php
protected $searchable = [
    'name',
    'category.name',  // Search in related model
];
```

### Relationship Filters

Map filter keys to relationship paths:

```php
protected $relationshipFilters = [
    'category' => 'category.name',      // Filter by category name
    'brand' => 'brand.id',               // Filter by brand ID
    'tag' => 'tags.name',                // Filter by tag name (many-to-many)
];
```

## Advanced Usage

### Custom Query Modifications

You can combine dynamic filters with custom query logic:

```php
public function getAllProducts(array $params = [])
{
    $query = Product::with('category')
        ->where('is_active', true)  // Custom condition
        ->whereHas('category', function ($q) {
            $q->where('is_active', true);
        });

    // Apply dynamic filters
    $query = $query->applyFilters($params);

    return $query->paginate($params['per_page'] ?? 15);
}
```

### Chaining Filters

The `applyFilters` method returns a query builder, so you can chain additional methods:

```php
$query = Product::applyFilters($params)
    ->where('featured', true)
    ->with('reviews')
    ->paginate(15);
```

## Security Considerations

1. **Always define `$filterable`** - Whitelist approach prevents filtering on sensitive fields
2. **Validate input** - Validate filter parameters in your Request classes
3. **Limit searchable fields** - Only include fields that should be searchable
4. **Use relationship filters carefully** - Ensure relationships are properly defined

## Best Practices

1. ✅ **Define filterable fields** - Always whitelist filterable fields
2. ✅ **Use appropriate operators** - Choose the right operator for the data type
3. ✅ **Index frequently filtered fields** - Add database indexes for performance
4. ✅ **Validate filter parameters** - Use Form Requests for validation
5. ✅ **Document filter options** - Document available filters in API docs
6. ✅ **Test edge cases** - Test with empty values, special characters, etc.

## Performance Tips

1. **Add indexes** on frequently filtered fields:
   ```php
   // Migration
   $table->index('status');
   $table->index('created_at');
   ```

2. **Use eager loading** to avoid N+1 queries:
   ```php
   $query = Product::with('category')->applyFilters($params);
   ```

3. **Limit searchable fields** to prevent slow queries on large tables

## Troubleshooting

### Filters not working

1. Check if field is in `$filterable` array
2. Verify field name matches exactly
3. Check if operator suffix is correct
4. Ensure value is not empty

### Relationship filters not working

1. Verify relationship is defined in model
2. Check `$relationshipFilters` mapping is correct
3. Ensure relationship path format: `relation.column`

### Performance issues

1. Add database indexes
2. Limit searchable fields
3. Use specific operators instead of `like` when possible
4. Consider pagination limits

---

**Last Updated**: 2025-01-XX

