PHP code example of netsells / eloquent-filters

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

    

netsells / eloquent-filters example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFilters;
}



namespace App\Features\Filters;

use Illuminate\Database\Eloquent\Builder;
use Netsells\EloquentFilters\Interfaces\FilterInterface;

class TitleFilter implements FilterInterface
{
    public function applyFilter(Builder $query, $value): void
    {
        $query->where('title', 'like', "%{$value}%");
    }
}

    /*
    |--------------------------------------------------------------------------
    | Model Filter Registration
    |--------------------------------------------------------------------------
    | This config file is used to register eloquent filters against
    | a query parameter.
    |
    | Model::class => [
    |      'query_parameter' => Filter::class,
    | ],
    |
    */

    'filters' => [
        Post::class => [
            'title' => TitleFilter::class,
        ],
    ],



namespace App\Features\Filters;

use Illuminate\Database\Eloquent\Builder;
use Netsells\EloquentFilters\Interfaces\FilterInterface;
use Netsells\EloquentFilters\Attributes\FiltersModel;

#[FiltersModel(Post::class, 'title')]
class TitleFilter implements FilterInterface
{
    public function applyFilter(Builder $query, $value): void
    {
        $query->where('title', 'like', "%{$value}%");
    }
}

Route::get('/', function () {
    return Post::applyFilters([
            'title' => 'Laravel'
        ])->get();
});

Route::get('/', function (Request $request) {
    return Post::applyFilters($request->all())->get();
});

Route::get('/', function (Request $request) {
    return Post::applyFilters($request->validated())->get();
});

Route::get('/', function (Request $request) {
    return Post::applyFilters($request->only('title'))->get();
});

Route::get('/', function (Request $request) {
    $collection = collect(['title' => 'laravel']);
    return Post::applyFilters($collection)->get();
});

php artisan vendor:publish --tag=eloquent-filters