mohammad-fouladgar / eloquent-builder

This package provides an advanced filter for Laravel model based on incoming requets.
https://medium.com/@mohammadfouladgarphp/laravel-eloquent-filter-all-in-one-d903ededbd19
MIT License
518 stars 42 forks source link

Non data get on bool values filters #73

Closed sxzero closed 4 years ago

sxzero commented 4 years ago

I have a model Products, where in my DB I store a tinyinteger field enable that accepts only 0 or 1.

Query /products/search?enable=true

I tried to get the data from:

$router->get('/products/search', 'SearchController@filter');

In my controller I have:

namespace App\Http\Controllers;

use App\Product;
use Illuminate\Http\Request;
use Fouladgar\EloquentBuilder\Facade as EloquentBuilder;

class SearchController extends Controller
{
    public function filter(Request $request)
    {
        $products = EloquentBuilder::to(Product::class, $request->all());

        return $products->get();
    }
}

And my filter file have this:

namespace App\EloquentFilters\Product;

use Fouladgar\EloquentBuilder\Support\Foundation\Contracts\Filter;
use Illuminate\Database\Eloquent\Builder;

class EnableFilter extends Filter
{
    /**
     * Apply the condition to the query.
     *
     * @param mixed $value
     */
    public function apply(Builder $builder, $value): Builder
    {
            return $builder->where('enable', $value);
    }
}

And always the response is empty.

But, If I tried directly with

return Product::where('enable', true|false);

Returns the content.

Dev Packages

"php": "^7.2.5",
"laravel/lumen-framework": "^7.0",
"mohammad-fouladgar/eloquent-builder": "^2.2"
sxzero commented 4 years ago

Also I tried to get the data converting the string $value to bool, changing the where query with numbers and operators but it fails too.

mohammad-fouladgar commented 4 years ago

@sxzero Use filter_var function in your filter:

public function apply(Builder $builder, $value): Builder
{
    return $builder->where('enable', filter_var($value, FILTER_VALIDATE_BOOLEAN));
}

See here for more details.

mohammad-fouladgar commented 4 years ago

@sxzero I close this issue, but feel free to reopen it if you need.