Eloquent & Data Access v2

Tweak Filter Behaviour

Laravel Model Filter · A Laravel package for filtering and searching models from database with ease.

Version and pages

You are reading version v2. The current documentation is v4.

Commit 47f72d9227c5 This page on GitHub

Sometimes you don't need a direct match between filter values and database. For example if you want a SelectFilter for Verified and Unverified users, but the database doesn't contain a bool or string-value but kind of an email_verified_at date field that implicit means a user is verified if this field is not null.

You can extend the available filters with own query logic. First create a SelectFilter as usual.

php artisan make:filter UserVerified -t select -f email_verified_at

Then add option values like usual and additionally extend the filters query function

<?php

namespace App\Models\Filters;

use Illuminate\Database\Eloquent\Builder;
use Lacodix\LaravelModelFilter\Filters\SelectFilter;

class UserVerifiedFilter extends SelectFilter
{
    protected string $field = 'email_verified_at';

    public function options(): array
    {
        return [
            'verified',
            'unverified',
        ];
    }

    public function apply(Builder $query): Builder
    {
        return match($this->values[$this->field]) {
            'verified' => $query->whereNotNull($this->field),
            'unverified' => $query->whereNull($this->field),
            default => $query,
        };
    }
}

Technical consultation

A package as a building block for your application.

If architecture, integration or operations are critical, let’s discuss your application as a whole.

Discuss your project