PHP code example of pradeepdev001 / laravel-smart-filter

1. Go to this page and download the library: Download pradeepdev001/laravel-smart-filter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pradeepdev001 / laravel-smart-filter example snippets


// Before
User::query()
    ->when($request->status, fn ($q, $v) => $q->where('status', $v))
    ->when($request->input('age>'), fn ($q, $v) => $q->where('age', '>', $v))
    ->when($request->country, fn ($q, $v) => $q->whereIn('country', explode(',', $v)))
    ->whereHas('posts', fn ($q) => $q->where('status', $request->posts_status))
    ->orderBy('created_at', 'desc')
    ->paginate();

// After
User::smartFilter()->paginate();

use Pradeepdev\SmartFilter\Traits\Filterable;

class User extends Model
{
    use Filterable;

    // Whitelist filterable fields (empty = all allowed)
    protected array $filterable = ['name', 'email', 'status', 'age', 'country'];

    // Fields searched by ?search=
    protected array $searchable = ['name', 'email'];

    // Protect sensitive columns
    protected array $filterIgnore = ['password', 'remember_token'];

    // Map request params to real columns
    protected array $filterAliases = ['city' => 'address_city'];
}

public function index(): JsonResponse
{
    return User::smartFilter()->paginate();
}

User::where('tenant_id', auth()->id())->smartFilter()->paginate();

class User extends Model
{
    use Filterable;

    protected array $filterable = ['name', 'email', 'status'];

    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class);
    }
}

return [
    'allowed_fields'    => [],               // Global whitelist (empty = all allowed)
    'ignored_fields'    => ['password'],     // Always blocked
    'aliases'           => [],               // ['city' => 'address_city']
    'searchable_fields' => [],               // Default ?search= fields
    'sort_param'        => 'sort',           // Query param for sorting
    'search_param'      => 'search',         // Query param for search
    'strict'            => false,            // Throw on unknown fields
    'operators'         => [],               // Custom operator classes
    'debug'             => false,            // Log parsed filters + SQL
];

use Pradeepdev\SmartFilter\Facades\SmartFilter;
use Pradeepdev\SmartFilter\Contracts\OperatorContract;
use Pradeepdev\SmartFilter\DTOs\FilterInput;
use Illuminate\Database\Eloquent\Builder;

class StartsWithOperator implements OperatorContract
{
    public function apply(Builder $builder, FilterInput $input): Builder
    {
        return $builder->where($input->field, 'LIKE', $input->value . '%');
    }

    public function handles(): array
    {
        return ['starts_with'];
    }
}

// In AppServiceProvider::boot()
SmartFilter::extend(new StartsWithOperator());

// config/smart-filter.php
'operators' => [App\Filters\StartsWithOperator::class],

User::smartFilter()->paginate(15);
User::smartFilter()->simplePaginate(15);
User::smartFilter()->cursorPaginate(15);

$request = Request::create('/users', 'GET', [
    'status'       => 'active',
    'posts.status' => 'published',
    'sort'         => '-created_at',
]);

$results = User::smartFilter($request)->get();