PHP code example of oooiik / laravel-query-filter

1. Go to this page and download the library: Download oooiik/laravel-query-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/ */

    

oooiik / laravel-query-filter example snippets


// Before — filtering logic leaking into the controller
$users = User::query()
    ->when($request->username, fn($q, $v) => $q->where('username', $v))
    ->when($request->role, fn($q, $v) => $q->whereHas('role', fn($r) => $r->where('title', $v)))
    ->when($request->created_after, fn($q, $v) => $q->where('created_at', '>=', $v))
    ->paginate();

// After — one line, all filtering in UserFilter
$users = User::filter($request->validated())->paginate();

namespace App\Filters;

use Oooiik\LaravelQueryFilter\Filters\QueryFilter;

class UserFilter extends QueryFilter
{
    public function username($username)
    {
        $this->builder->where('username', $username);
    }

    public function role($role)
    {
        $this->builder->whereHas('role', function ($query) use ($role) {
            $query->where('title', $role);
        });
    }

    public function createdAfter($date)
    {
        $this->builder->where('created_at', '>=', $date);
    }
}

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Oooiik\LaravelQueryFilter\Traits\Model\Filterable;
use App\Filters\UserFilter;

class User extends Model
{
    use Filterable;

    protected $defaultFilter = UserFilter::class;
}

// Controller
public function index(Request $request)
{
    $validated = $request->validate([
        'username'      => 'nullable|string',
        'role'          => 'nullable|string',
        'createdAfter'  => 'nullable|date',
    ]);

    return User::filter($validated)->paginate();
}

class UserFilter extends QueryFilter
{
    public $default = [
        'status' => 'active',
        'sort'   => 'created_at',
    ];

    public function status($status)
    {
        $this->builder->where('status', $status);
    }

    public function sort($column)
    {
        $this->builder->orderBy($column, 'desc');
    }
}

class UserFilter extends QueryFilter
{
    public $fallback = [
        'search' => 'searchByName',
    ];

    public function searchByName($value)
    {
        $this->builder->where('name', 'like', "%{$value}%");
    }
}

$filter = User::createFilter(UserFilter::class);

$filter->apply(['role' => 'admin']);
$filter->apply(['status' => 'active']);

$query = $filter->query();
// Both filter sets are now applied to the builder

public function username($username, $allParams)
{
    if (! empty($allParams['exact_match'])) {
        $this->builder->where('username', $username);
    } else {
        $this->builder->where('username', 'like', "%{$username}%");
    }
}