Git Product home page Git Product logo

filterable's Introduction

Filterable

About Filterable

Latest Version on Packagist Tests Check & fix styling Total Downloads

The Filter class provides a flexible and powerful way to apply dynamic filters to Laravel's Eloquent queries. It supports caching, user-specific filtering, and custom filter methods, making it suitable for a wide range of applications, from simple blogs to complex data-driven platforms.

Features

  • Dynamic Filtering: Apply filters based on request parameters with ease.
  • Caching: Improve performance by caching query results.
  • User-specific Filtering: Easily implement filters that depend on the authenticated user.
  • Custom Filter Methods: Extend the class to add your own filter methods.

Installation

To integrate the Filterable package into your Laravel project, you can install it via Composer. Run the following command in your project directory:

composer require jerome/filterable

Upon installation, the package should automatically register its service provider with Laravel's service container, making its features readily available throughout your application. This leverages Laravel's package auto-discovery mechanism, which is supported in Laravel 5.5 and later versions.

If you are using a version of Laravel that does not support package auto-discovery, you will need to manually register the FilterableServiceProvider in your config/app.php file, under the providers array:

'providers' => [
    // Other service providers...

    Filterable\Providers\FilterableServiceProvider::class,
],

This step is typically not necessary for modern Laravel installations, as auto-discovery should handle it for you.

After installation and registration, you're ready to use the Filterable features to enhance your Laravel application's data querying capabilities.

Usage

Creating a Filter Class

You can create a new filter class using the following Artisan command:

php artisan make:filter PostFilter

This command will generate a new filter class in the app/Filters directory. You can then customise this class to add your own filter methods.

The Filter class is a base class that provides the core functionality for applying filters to Eloquent queries. You can extend this class to create your own filter classes tailored to your specific models. To use the Filter class, you first need to extend it to create your own filter class tailored to your specific model. Here's a basic example for a Post model:

namespace App\Filters;

use Filterable\Filter;
use Illuminate\Database\Eloquent\Builder;

class PostFilter extends Filter
{
    protected array $filters = ['status', 'category'];

    protected function status(string $value): Builder
    {
        return $this->builder->where('status', $value);
    }

    protected function category(int $value): Builder
    {
        return $this->builder->where('category_id', $value);
    }
}

To add a new filter, simply define a new method within your custom filter class. This method should adhere to PHP's camelCase naming convention and be named descriptively based on the filter's purpose. Once you've implemented the method, ensure to register its name in the $filters array to activate it. Here's how you can do it:

namespace App\Filters;

use Filterable\Filter;

class PostFilter extends Filter
{
    protected array $filters = ['last_published_at'];

    protected function lastPublishedAt(int $value): Builder
    {
        return $this->builder->where('last_published_at', $value);
    }
}

In this example, a new filter lastPublishedAt is created in the PostFilter class. The filter name last_published_at is registered in the $filters array.

Implementing the Filterable Trait and Filterable Interface

To use the Filter class in your Eloquent models, you need to implement the Filterable interface and use the Filterable trait. Here's an example for a Post model:

namespace App\Models;

use Filterable\Interfaces\Filterable as FilterableInterface;
use Filterable\Traits\Filterable as FilterableTrait;
use Illuminate\Database\Eloquent\Model;

class Post extends Model implements FilterableInterface
{
    use FilterableTrait;
}

Note: The Filterable interface and Filterable trait are included in the package and should be used in your models to enable filtering. The Filterable interface is optional but recommended for consistency.

Applying Filters

You can apply filters to your Eloquent queries like so:

use App\Models\Post;

$filter = new PostFilter(request(), cache());
$posts = Post::filter($filter)->get();

Applying Filters in Controllers

You can apply your custom filters in your controller methods like so:

use App\Models\Post;
use App\Filters\PostFilter;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index(Request $request, PostFilter $filter)
    {
        $query = Post::filter($filter);

        $posts = $request->has('paginate')
            ? $query->paginate($request->query('per_page', 20))
            : $query->get();

        return response()->json($posts);
    }
}

Applying Filters Scoped to the Authenticated User

You can also apply filters that are specific to the authenticated user. The forUser method sets the user for which the filters should be applied:

use App\Models\Post;
use App\Filters\PostFilter;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index(Request $request, PostFilter $filter)
    {
        $filter->forUser($request->user());

        $query = Post::filter($filter);

        $posts = $request->has('paginate')
            ? $query->paginate($request->query('per_page', 20))
            : $query->get();

        return response()->json($posts);
    }
}

Applying Pre-Filters to run before the main filters

You can also apply pre-filters that run before the main filters. The registerPreFilters method sets the pre-filters that should be applied:

use App\Models\Post;
use App\Filters\PostFilter;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;

class PostController extends Controller
{
    public function index(Request $request, PostFilter $filter)
    {
        $filter->registerPreFilters(function (Builder $query) {
            return $query->where('published', true);
        });

        $query = Post::filter($filter);

        $posts = $request->has('paginate')
            ? $query->paginate($request->query('per_page', 20))
            : $query->get();

        return response()->json($posts);
    }
}

Using Filters on the Frontend

You can use filters on the frontend by sending a request with query parameters. For example, to filter posts by status, you can send a request like this:

const response = await fetch('/posts?status=active');

const data = await response.json();

This request will return all posts with the status active.

You can also string together all the filters you want to apply. For example, to filter posts by status and category, you can send a request like this:

const response = await fetch('/posts?status=active&category_id=2');

const data = await response.json();

This request will return all posts with the status active and associated with the category of ID 2.

Note: Any query parameters that do not match the filter names will be ignored.

Caching

In your filter class, you can control caching by using the enableCaching static method. Set the $useCache static property to true to enable caching, or false to disable it. You can also customise the duration of the cache by modifying the $cacheExpiration property.`

Note: Caching is disabled by default.

/**
 * Indicates if caching should be used.
 *
 * @var bool
 */
protected static bool $useCache = false;

Enabling and Disabling Caching

  • Enable Caching: To start caching, ensure that caching is enabled. This is typically done during the setup or dynamically based on the application context, such as only enabling caching in a production environment to improve performance and reduce database load.
// AppServiceProvider.php

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot(): void
{
    // Enable caching globally through methods...
    Filter::enableCaching();
}
  • Disable Caching: If you need to turn off caching temporarily, for example, during development to ensure fresh data is loaded on each request and to aid in debugging, you can disable it:
// AppServiceProvider.php

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot(): void
{
    // Disable caching globally through methods...
    Filter::disableCaching();
}

This configuration allows you to manage caching settings centrally from the AppServiceProvider. Adjusting caching behavior based on the environment or specific scenarios helps optimize performance and resource utilization effectively.

namespace App\Filters;

use Filterable\Filter;

class PostFilter extends Filter
{
    protected array $filters = ['last_published_at'];

    protected function lastPublishedAt(int $value): Builder
    {
        return $this->builder->where('last_published_at', $value);
    }
}

$filter = new PostFilter(request(), cache());

// Control caching
$filter->setCacheExpiration(1440); // Cache duration in minutes

Certainly! Here’s a detailed usage guide section that explains how to utilize the logging functionality in the Filter class. This guide is designed to help developers understand and implement logging within the context of filtering operations effectively.

Logging

The Filter class incorporates robust logging capabilities to aid in debugging and monitoring the application of filters to query builders. This functionality is crucial for tracing issues, understanding filter impacts, and ensuring the system behaves as expected.

Configuring the Logger

  1. Setting Up Logger: Before you can log any activities, you must provide a logger instance to the Filter class. This logger should conform to the Psr\Log\LoggerInterface. Typically, this is set up in the constructor or through a setter method if the logger might change during the lifecycle of the application.
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Create a logger instance
$logger = new Logger('name');
$logger->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// Set the logger to the filter class
$filter->setLogger($logger);
  1. Dependency Injection: If you are using Laravel, you can leverage its service container to automatically inject the logger into your Filter class.
// In a service provider or similar setup
$this->app->when(Filter::class)
    ->needs(LoggerInterface::class)
    ->give(function () {
        return new Logger('name', [new StreamHandler('path/to/your.log', Logger::WARNING)]);
    });

Setting Up Logger with a Custom Channel

You can set up a specific logging channel for your Filter class either by configuring it directly in the logger setup or by defining it in Laravel’s logging configuration and then injecting it. Here’s how to do it in both ways:

  1. Direct Configuration:

    • Directly create a logger with a specific channel and handler. This method is straightforward and gives you full control over the logger’s configuration:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Create a logger instance for the Filter class with a custom channel
$logger = new Logger('filter');
$logger->pushHandler(new StreamHandler(storage_path('logs/filter.log'), Logger::DEBUG));

// Set the logger to the filter class
$filter->setLogger($logger);
  1. Using Laravel's Logging Configuration:

    • Laravel allows you to define custom channels in its logging configuration file (config/logging.php). You can define a specific channel for the Filter class there and then retrieve it using the Log facade:
// In config/logging.php

'channels' => [
    'filter' => [
        'driver' => 'single',
        'path' => storage_path('logs/filter.log'),
        'level' => 'debug',
    ],
],
  • Now, you can set this logger in your service provider or directly in your class using the Log facade:
use Illuminate\Support\Facades\Log;

// In your AppServiceProvider or wherever you set up the Filter class
$filter->setLogger(Log::channel('filter'));

Enabling and Disabling Logging

  • Enable Logging: To start logging, ensure that logging is enabled. This is typically done during setup or dynamically based on application context (e.g., only logging in a development environment).
// AppServiceProvider.php

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot(): void
{
    // Enable logging globally through methods...
    Filter::enableLogging();
}
  • Disable Logging: If you need to turn off logging temporarily (e.g., in a production environment to improve performance), you can disable it:
// AppServiceProvider.php

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot(): void
{
    // Disable logging globally through methods...
    Filter::disableLogging();
}

Logging Actions

  • Automatic Logging: Once the logger is set and enabled, the Filter class will automatically log relevant actions based on the methods being called and the filters being applied. This includes logging at various points such as when filters are added, when queries are executed, and when cache hits or misses occur.

  • Custom Logging: You can add custom logging within the filters you define or by extending the Filter class. This can be useful for logging specific conditions or additional data that the default logging does not cover.

public function customFilter($value) {
    if (self::shouldLog()) {
        $this->getLogger()->info("Applying custom filter with value: {$value}");
    }
    // Filter logic here
}

Checking If Logging Is Enabled

  • Conditional Logging: Before logging any custom messages, check if logging is enabled to avoid unnecessary processing or logging errors.
if (Filter::shouldLog()) {
    $this->getLogger()->info('Performing an important action');
}

Testing

Testing your filters can be done using PHPUnit. Here’s an example test that ensures a status filter is applied correctly:

namespace Tests\Unit;

use Tests\TestCase;
use App\Models\Post;
use App\Filters\PostFilter;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;

class PostFilterTest extends TestCase
{
    use RefreshDatabase;

    public function testFiltersPostsByStatus(): void
    {
        $activePost = Post::factory()->create(['status' => 'active']);
        $inactivePost = Post::factory()->create(['status' => 'inactive']);

        $filter = new PostFilter(new Request(['status' => 'active']));
        $filteredPosts = Post::filter($filter)->get();

        $this->assertTrue($filteredPosts->contains($activePost));
        $this->assertFalse($filteredPosts->contains($inactivePost));
    }
}

Ensure you have the necessary testing environment set up, including any required migrations or factory definitions.

License

This project is licensed under the MIT License - see the LICENSE.md file for details.

Contributing

Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repository and create a pull request. You can also simply open an issue with the tag "enhancement".

Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/amazing-feature)
  3. Commit your Changes (git commit -m 'Add some amazing-feature')
  4. Push to the Branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Authors

  • [Jerome Thayananthajothy] - Initial work - Thavarshan

See also the list of contributors who participated in this project.

Acknowledgments

  • Hat tip to Spatie for their query builder package, which inspired this project.

filterable's People

Contributors

dependabot[bot] avatar github-actions[bot] avatar thavarshan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

filterable's Issues

Dependency Conflict with `nesbot/carbon` When Installing `jerome/filterable`

Description:

While attempting to install the jerome/filterable package via Composer, I encountered a dependency resolution conflict. The composer.json requires jerome/filterable at any version (*), which in turn requires nesbot/carbon at ^2.72. However, the currently installed version of nesbot/carbon is 3.2.4, as specified by the lock file, leading to an unresolvable set of package requirements.

Steps to Reproduce:

  1. Run the Composer command composer require jerome/filterable.
  2. Encounter a dependency conflict due to the installed version of nesbot/carbon.

Expected Behavior:

The jerome/filterable package should be installed without conflicts, or the required version constraints should be clearly specified.

Actual Behavior:

Installation fails due to a dependency version conflict with nesbot/carbon.

Error Message:

Problem 1
- Root composer.json requires jerome/filterable * -> satisfiable by jerome/filterable[1.0.0].
- jerome/filterable 1.0.0 requires nesbot/carbon ^2.72 -> found nesbot/carbon[2.72.0, 2.72.1, 2.72.2, 2.72.3] but the package is fixed to 3.2.4 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.

Suggested Fix:

One potential fix would be to update the jerome/filterable package's composer.json to allow compatibility with nesbot/carbon version 3.2.4 if this version is supported.

Additional Context:

  • PHP version: 8.3
  • Composer version: 2.7.2
  • Operating System: MacOS Sonoma 14.4.1 (23E224)

Screenshot 2024-04-10 at 1 33 18 AM

Artisan `make:filter` Command Does Not Accept Arguments

Issue Description:

When trying to use the artisan command make:filter to create a new filter class, I encounter an error stating that no arguments are expected for the command, even though I am passing the name of the filter class as an argument.

Command Run:

php artisan make:filter CourseFilter

Error Received:

No arguments expected for "make:filter" command, got "CourseFilter".

Expected Behavior:

The make:filter command should accept the class name as an argument and generate a new filter class with the provided name.

Actual Behavior:

The command throws an error indicating that it does not expect any arguments.

Steps to Reproduce:

  1. Run php artisan make:filter CourseFilter in the terminal.
  2. Observe the error message indicating that no arguments were expected.

Possible Causes:

  • There might be a misunderstanding of how the make:filter command is supposed to work.
  • The command definition for make:filter may not be set up to accept arguments.
  • There could be a version mismatch or a custom command that overrides the expected behavior.

Suggested Solution:

Review the definition of the make:filter command to ensure that it is set up to take a class name as an argument. If this is a custom command, the signature may need to be updated to include the expected argument.

Environment:

  • Laravel version: 11.3
  • PHP version: 8.3.4

Additional Context:

  • Provide any additional information that could be helpful, like recent changes to the artisan commands or relevant configuration files.

Screenshot 2024-04-10 at 11 04 00 AM

`filter` Method Not Recognised on Eloquent Model Query Builder

Issue Description:

When attempting to apply the filter method to an Eloquent model query, an error is thrown indicating that the method is undefined. The expected behavior is that the filter method, presumably a local scope, should apply the provided CourseFilter to the Course::query() but instead, the following error is encountered:

BadMethodCallException
Call to undefined method Illuminate\Database\Eloquent\Builder::filter()

Steps to Reproduce:

  1. Create a filter class named CourseFilter.
  2. Attempt to use this filter with the Course model like so:
$courses = Course::query()->filter($filter)->get();
  1. An exception is thrown stating that the filter method is not defined on the builder instance.

Expected Behavior:

The filter method should be recognized as a local scope on the Course model and should filter the results based on the implementation of the CourseFilter.

Actual Behavior:

A BadMethodCallException is thrown because the filter method is not recognized.

Error Message:

BadMethodCallException
Call to undefined method Illuminate\Database\Eloquent\Builder::filter()
Did you mean Illuminate\Database\Eloquent\Builder::firstWhere() ?

Suggested Fix:

Ensure that the filter method is correctly defined as a local scope in the Course model or that any trait containing the scope is properly used in the model.

Additional Context:

  • Laravel version: 11.3
  • PHP version: 8.3.4
  • Full stack trace of the error.
  • Confirmation that the CourseFilter is set up correctly and is being used properly.

Screenshot 2024-04-10 at 8 25 51 PM

Fatal Error: Type of `App\Filters\EventFilter::$filters` Must Be Array

Issue Description:

When using the EventFilter class that extends Filterable\Filter, a fatal error occurs due to a type mismatch with the property $filters. The error states that $filters must be of type array, as expected by the Filterable\Filter class, but it appears to be set to a different type or not properly initialized as an array.

Error Message:

Symfony\Component\ErrorHandler\Error\FatalError
Type of App\Filters\EventFilter::$filters must be array (as in class Filterable\Filter)

Steps to Reproduce:

  1. Define an EventFilter class that extends Filterable\Filter.
  2. Attempt to apply the filter in a query.
  3. Encounter the fatal error due to a type mismatch with $filters.

Expected Behavior:

The EventFilter class should be able to declare $filters as an array, and the filter functionality should work as intended without any type errors.

Actual Behavior:

A fatal error is thrown because of a type mismatch, preventing the proper use of the filtering functionality.

Code Snippet:

The EventFilter class is defined as follows:

namespace App\Filters;

use Filterable\Filter;
use Illuminate\Database\Eloquent\Builder;

class EventFilter extends Filter
{
    protected $filters = ['filter'];

    protected function filter(string $value): Builder
    {
        return $this->builder->where('column', $value);
    }
}

Possible Solution:

Ensure that $filters is properly typed as an array. If there are default values or initialisations, they should be in an array format. For example:

protected array $filters = ['filter'];

Additional Context:

  • PHP version: 8.3.4
  • Laravel version: 11.3

Class `Filterable\FilterableServiceProvider` Not Found After Installation

Issue Description:

After installing the jerome/filterable package at version ^1.0, a class not found exception is thrown during the post-installation script execution. Specifically, the error states that the Filterable\FilterableServiceProvider class is not found, which suggests an issue with the service provider registration or autoloading.

Steps to Reproduce:

  1. Require the jerome/filterable package by running composer require jerome/filterable="^1.0".
  2. After installation, observe the error during the php artisan package:discover --ansi command execution.

Expected Behavior:

The jerome/filterable package should be installed without any errors, and all service providers should be discovered and registered without issues.

Actual Behavior:

The installation process throws the following error:

In ProviderRepository.php line 206:
Class "Filterable\FilterableServiceProvider" not found

This error occurs during the php artisan package:discover --ansi script, which is part of the post-autoloading dump.

Error Message:

Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Possible Solutions:

  • Check if the FilterableServiceProvider class exists within the package.
  • Verify that the composer.json of jerome/filterable has the correct autoload configuration.
  • Ensure that the package's service provider is correctly namespaced.

Additional Context:

  • PHP version: 8.3.4
  • Composer version: 2.7.2
  • Laravel version: 11.3

Screenshots/Logs:

Screenshot 2024-04-10 at 10 35 29 AM

Cache pollution issue when switching between query parameters

  • App Version: 1.1.1
  • PHP Version: 8.2.0 / 8.3.4
  • Database Driver & Version: MySQL 8.0

Description

We are encountering an issue in our "filterable" Laravel package where cached results are incorrectly mixed between different query parameters. Specifically, after switching back to a previously made query, the cached results include data from both the current and previous queries.

Steps To Reproduce

  1. Send a GET request to /booking?status=pending. The correct, status-pending bookings are returned.
  2. Send a subsequent GET request to /booking?status=completed. The correct, status-completed bookings are returned.
  3. Reissue the first GET request to /booking?status=pending.

Expected Result: Only bookings with 'pending' status should be returned.
Actual Result: Bookings with both 'pending' and 'completed' statuses are returned, indicating a caching issue where the cache does not differentiate sufficiently between different queries.

Proposed Solution

Enhance Cache Key Generation

Modify the buildCacheKey() function to include all relevant query parameters in the cache key generation. This would ensure that each unique set of parameters has its own cache entry, preventing cache pollution.

protected function buildCacheKey(): string
{
    $userPart = optional($this->forUser)->getAuthIdentifier() ?? 'global';
    $filtersPart = http_build_query($this->getFilterables());
    return "filters:{$userPart}:{$filtersPart}";
}

JSON to Laravel Eloquent Filters

Introduce an advanced filter logic system to allow for complex and nested filtering conditions using logical operators like AND, OR, and NOT. This feature would significantly enhance the capability of dynamic query generation based on user inputs, making the filter system more powerful and flexible.

Description:
Currently, the package supports simple key-value pair filtering which is adequate for basic needs. However, for more sophisticated applications such as analytics platforms, complex searches, or user-driven data exploration, there is a need for more complex query capabilities.

Proposed Solution:
Implement a JSON-based filter definition system that allows users to define filters with logical operators and nested conditions. Here is an overview of the proposed feature:

  1. JSON-Based Filter Definitions:
    • Users can define filters using a structured JSON format, allowing for logical combinations and nested conditions. These definitions could be provided via API endpoints, configuration files, or directly within the application code.
  2. Filter Parser:
    • Develop a parser that interprets the JSON input and translates it into SQL conditions or Eloquent query builder statements, handling recursion to support nested conditions.
  3. Custom Query Builder Extensions:
    • Extend Laravel's Query Builder with custom methods such as applyComplexFilter to handle complex logical expressions, ensuring each condition group is applied correctly based on the parsed filter definitions.

Challenges:

  • Performance: Optimize query execution and consider caching strategies for heavy queries.
  • Security: Ensure rigorous input validation and sanitization to prevent SQL injection and unauthorized data access, using Laravel’s parameterized queries and other built-in mechanisms.
  • Usability: Offer clear documentation and API reference to help users utilize complex filters effectively.

Use Cases:

  • E-commerce Platforms: Enable detailed product searches combining attributes like price, categories, brands, and availability. For example, users could filter products that are within a specific price range and belong to multiple selected categories.
  • CRM Systems: Allow users to generate detailed reports or find specific customer segments by applying complex filters to customer data, such as filtering clients based on engagement metrics combined with demographic data.

Additional Notes: This feature would make the filter system a robust tool for developers creating complex and data-intensive applications, providing significant value and enhancing the flexibility of data manipulation.

Example:

{
   "logic": "AND",
   "filters": [
      {
         "field": "price",
         "operator": ">",
         "value": 100
      },
      {
         "logic": "OR",
         "filters": [
            {
               "field": "category",
               "operator": "=",
               "value": "Electronics"
            },
            {
               "field": "category",
               "operator": "=",
               "value": "Clothing"
            }
         ]
      }
   ]
}

In this example, the filter defines a condition where the price is greater than 100 and the category is either "Electronics" or "Clothing". This demonstrates the power of combining logical operators and nested conditions to create sophisticated filters.

Translating JSON to Eloquent Query:

  1. Parse the Root Logic Operator (AND):
    The root of this JSON specifies an AND logic operator, indicating that all contained conditions must be met. In Eloquent, this translates to chaining conditions together using where clauses.
  2. Interpret Individual Filters:
    • The first filter in the array specifies a condition on the price field. This is straightforward:
      ->where('price', '>', 100)
    • The second element contains an OR logic operator, which groups two conditions that can satisfy the query if either is true. In Eloquent, this is handled using the orWhere method, but to ensure it only applies to the conditions within its group, you use where with a closure, inside which you use orWhere:
        ->where(function($query) {
           $query->where('category', '=', 'Electronics')
                 ->orWhere('category', '=', 'Clothing');
        });

Complete Eloquent Query:

Combining these, the complete query built from the JSON looks like this:

$query = Model::query()  // Assuming you are querying a model
   ->where('price', '>', 100)
   ->where(function($query) {
      $query->where('category', '=', 'Electronics')
            ->orWhere('category', '=', 'Clothing');
   });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.