PHP code example of freebuu / laravel-filterable

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

    

freebuu / laravel-filterable example snippets


class PostIndexController
{
    public function __invoke(Request $request) 
    {
        $data = Post::requestFilter()->setResource(PostResource::class);
        return response()->json($data);
    }
}

class PostFilter extends AbstractFilter
{
    protected function getFilterableFields(FilterCaseEnum $case): array
    {
        return match ($case) {
            FilterCaseEnum::WHERE => ['publisher_id'],
            FilterCaseEnum::SORT => ['id'],
            FilterCaseEnum::WHERE_HAS => ['groups' => ['id']]
            default => []
        };
    }
}

class Post extends Model
{
    use HasRequestFilter;
    
    public function requestFilterClass(): string
    {
        return \App\Http\Filters\PostFilter::class;
    }
}

class PostFilter extends AbstractFilter
{
    public function filterCustom(Builder $builder, mixed $value, mixed $fieldValue): void
    {
        //you have request instance here
        if($this->request->query('something')){
            return;
        }
        //$value will be 123 
        //$fieldValue will be alias (or can be null)
        $builder->where('some_field', $value)->where($fieldValue, '432')
    }
}

class AppServiceProvider extends ServiceProvider
{
    public function register() 
    {
        AbstractFilter::$defaultMaxLimit = 50;
    }
}

Post::requestFilter()
    ->addQueryCallback(fn (Builder $builder) => $builder->where('author_id', auth()->id()))
    ->response(ResourceClass::class);