PHP code example of pointybeard / laravel-filterable-model

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

    

pointybeard / laravel-filterable-model example snippets


protected $filterable = ['title', 'category', 'tags', 'is_published'];
protected bool $sortable = true;
protected string $sortByDefault = 'published_at'; // default is 'created_at'
protected string $sortOrderDefault = 'desc'; // default is 'asc'

use App\Models\MyModel;
use Pointybeard\FilterableModel\Filter;

MyModel::filter(new Filter(
    filters: [
        'tag' => 'article',
        'is_published' => 1,
    ],
));


use App\Models\MyModel;
use Pointybeard\FilterableModel\Filter;

return response()->json(
    MyModel::filter(Filter::fromRequest($request))->get(),
    Response::HTTP_OK
);

use Pointybeard\FilterableModel\AbstractFilterableModel;
use Pointybeard\FilterableModel\Filter;
use Illuminate\Database\Eloquent\Builder;

Class MyModelFilter extends Filter
{
    public function tag(Builder $builder, AbstractFilterableModel $model, string $value): Builder
    {
        return $builder->where('tag', 'like', "%{$value}%");
    }

    public function is_published(Builder $builder, AbstractFilterableModel $model, string $value): Builder
    {
        // Convert a string representation of true/false into an actual boolean
        $value = in_array(strtolower($value), ['1', 'true', 'yes']) ? true : false;

        return $builder->where('protected', $value);
    }
}