Jun 12 2015

Encapsulating complex query conditions using QueryCriteria in Laravel

Category: Laravel,PHPFractalizeR @ 9:56 pm

Very often my query conditions in repositories become complicated. To be able to reuse them across repositories I use the following simple pattern:

interface CriteriaInterface
{
    /**
     * @param EloquentBuilder|QueryBuilder $query
     *
     * @return void
     */
    public function attach($query);
}

All my query conditions implement this interface and accept condition parameters in the constructor. For example, this is how CategoryCriteria looks like:

/**
 * Class CategoryCriteria
 *
 */
class CategoryCriteria implements CriteriaInterface
{
    /**
     * @var null|int|array
     */
    private $categoryId;
 
    /**
     * CategoryCriteria constructor.
     *
     * @param null|int|array $categoryId
     */
    public function __construct($categoryId)
    {
        $this->categoryId = $categoryId;
    }
 
    /**
     * @param null|int|array $categoryId
     *
     * @return LocationCriteria
     */
    public static function create($categoryId)
    {
        return new static($categoryId);
    }
 
    /**
     * @param EloquentBuilder|QueryBuilder $query
     */
    public function attach($query)
    {
        if (empty($this->categoryId)) {
            return;
        }
 
        if (is_array($this->categoryId)) {
            $query->whereIn('category_id', $this->categoryId);
        } else {
            $query->where('category_id', $this->categoryId);
        }
    }
}

Leave a Reply

You must be logged in to post a comment. Login now.