PHP code example of baethon / laravel-criteria

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

    

baethon / laravel-criteria example snippets


composer 



use Baethon\LaravelCriteria\CriteriaInterface;

class CompareCriteria implements CriteriaInterface
{
    private $field;

    private $value;

    public function __construct(string $field, string $value)
    {
        $this->field = $field;
        $this->value = $value;
    }

    public function apply($query)
    {
        $query->where($this->field, $this->value);
    }
}

$query = User::query();

(new CompareCriteria('name', 'Jon'))->apply($query);

$jon = $query->first();

use Baethon\LaravelCriteria\Traits\AppliesCriteria;

class User extends Model
{
    // model body stripped for better readability

    use AppliesCriteria;
}

$jon = User::query()
    ->apply(new CompareCriteria('name', 'Jon'))
    ->first();

$jonSnow = User::query()
    ->apply(CriteriaCollection::create([
        new CompareCriteria('name', 'Jon'),
        new CompareCriteria('lastname', 'Snow'),
    ]))
    ->first();

// same result, without CriteriaCollection
$jonSnow = User::query()
    ->apply(new CompareCriteria('name', 'Jon'))
    ->apply(new CompareCriteria('lastname', 'Snow'))
    ->first();

User::query()
    ->apply(CriteriaCollection::allOf([
        new CompareCriteria('name', 'Jon'),
        new CompareCriteria('lastname', 'Snow'),
    ]));

// same as
User::query()
    ->where(function ($query) {
        $query->apply(new CompareCriteria('name', 'Jon'))
            ->apply(new CompareCriteria('lastname', 'Snow'));
    });

User::query()
    ->apply(CriteriaCollection::oneOf([
        new CompareCriteria('name', 'Jon'),
        new CompareCriteria('lastname', 'Snow'),
    ]));

// same as
User::query()
    ->where(function ($query) {
        $query->where('name', 'Jon')
            ->orWhere('lastname', 'Snow');
    });