PHP code example of mohamedfathy / dynamic-filters

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

    

mohamedfathy / dynamic-filters example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use MohamedFathy\DynamicFilters\HasDynamicFilters;

class Product extends Model
{
    use HasDynamicFilters;

    /**
     * Define the fields that can be filtered dynamically.
     * Only these attributes can be used in query filters.
     */
    protected array $allowedFilters = ['name', 'price', 'category'];

    /**
     * Define the relationships that are allowed for filtering or eager loading.
     * Only these relations can be 

/**
 * list products.
 *
 * @param Request $request
 * @return JsonResponse
 */
public function index(Request $request): JsonResponse
{
    // The $request->all() resolves to an array like: ['filters' => ['category:eq' => 'electronics']]
    $data = Product::filter($request->all())->get();
    return response()->json($data);
}



namespace App\Filters;

use Illuminate\Database\Eloquent\Builder;

class ProductFilters
{
    protected Builder $query;

    public function __construct(Builder $query)
    {
        $this->query = $query;
    }

    /**
     * get most expensive product for each provider.
     */
    public function mostExpensiveProductsByProvider($providerId): void
    {
        $this->query->select(
            'products.id',
            'products.name',
            'products.price',
            'providers.name as provider_name'
        )
            ->join('providers', 'products.provider_id', '=', 'providers.id')
            ->where('products.is_published', true)
            ->where('products.provider_id' , $providerId)
            ->orderBy('products.price', 'DESC');

    }
}