PHP code example of laraditz / model-filter

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

    

laraditz / model-filter example snippets


use Laraditz\ModelFilter\Filterable;

class User extends Model
{
    use Filterable;

    protected array $filterable = [
        'name',
        'email',
        'age',
        'role.name',  // dot-notation opts in to relationship filtering
    ];

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

namespace App\Filters;

use Laraditz\ModelFilter\Filter;

class UserFilter extends Filter
{
    public function name(mixed $value): void
    {
        $this->query->where('name', 'LIKE', $value . '%');
    }
}

$users = User::filter($request->all())->get();

protected array $filterable = [
    'name',
    'role.name',   // enables ?filters[role.name][...]=...
];

class UserFilter extends Filter
{
    /**
     * ?filters[active_admin]=1
     * Finds users with an active role named "admin".
     */
    public function activeAdmin(mixed $value): void
    {
        if (! $value) {
            return;
        }

        $this->query->whereHas('role', function ($q): void {
            $q->where('name', 'admin')
              ->where('active', true);
        });
    }
}

protected array $filterable = ['active_admin'];