Skip to content
This repository has been archived by the owner on Jun 3, 2023. It is now read-only.
/ criteria-builder Public archive

Build criteria builder for Query Builder and Eloquent Builder

License

Notifications You must be signed in to change notification settings

reishou/criteria-builder

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CRITERIA BUILDER

Build criteria builder for Laravel by different way.

Requirements

  • PHP >= 7.0
  • Laravel >= 5.x

Installation

composer require reishou/criteria-builder

Usage

First, you need to create a class extends abstract Reishou\Criteria\Criteria

<?php

namespace App\Criteria;

use Reishou\Criteria\Criteria;

class UserCriteria extends Criteria
{
    protected $criteria = [
        'status',
        'name' => 'like',
        'age',
    ];
}

Then, you can use it

$param = ['status' => [1, 3], 'name' => 'Reishou', 'age' => 30];

$query = User::query();
$criteria = new UserCriteria($param);
$criteria->apply($query);

$query->get();

Result is list users who have status 1 or 3, name "like" Reishou and age = 30. Default, criteria will apply where clause with AND operator. If you want to use where clause with OR operator, you should make a custom method.

Custom method

Add a function to UserCriteria with pattern criteria{KeyNameWithStudlyCapsFormat}

protected function criteriaStatus($query, $value)
{
    $statuses = is_array($value) ? $value : [$value];
    $query->where(function ($query) use ($statuses) {
        foreach ($statuses as $status) {
            $query->orWhere($this->getTable() . '.status', $status);
        }
    });
}

Sort options

Beside, we can use SortOptions to set some sort rules

/GET <URL>/users?sort=-status,name 

Create a class UserSortOptions extends Reishou\Criteria\SortOptions

class UserSortOptions extends SortOptions
{
    protected $sorts = [
        'status',
        'name',
    ];

    protected $default = [
        ['status', 'desc'],
        ['name', 'asc'],
    ];
}

$sorts is an array that contains fields be sortable.

Use UserSortOptions like as using UserCriteria

$param = ['sort' => '-status,name'];

$sort  = new UserSortOptions($param);
$query = User::query();
$sort->apply($query);

$query->get();

-status means sort column status and order by desc name means sort column name and order by asc

Testing

Run tests with:

./vendor/bin/phpunit

License

The MIT License (MIT). Please see License File for more information.

About

Build criteria builder for Query Builder and Eloquent Builder

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages