PHP code example of sergyjar / laravel-query-builder

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

    

sergyjar / laravel-query-builder example snippets



namespace App\Path\For\File;

use App\Models\ModelName;
use Sergyjar\QueryBuilder\AbstractQueryBuilder;

class ModelNameQueryBuilder extends AbstractQueryBuilder
{
    protected array $filterableFields = [
        //
    ];
    
    protected array $sortMap = [
        //
    ];

    protected function getModelClass(): string
    {
        return ModelName::class;
    }
}

protected array $filterableFields = [
 'fieldName'
];

protected array $filterableFields = [
    'field_name'
];

protected array $filterableFields = [
    'status'
];

public function status($value): void
{
    if ($value == 'pending') {
        $this->query->whereStatus($value)
    }
}

    protected array $sortMap = [
        //
    ];

    protected array $sortMap = [
        'status' => 'status_id'
    ];

$query = new ModelQueryBuilder($params);

$result = $query
    ->setFilters()
    ->setSort()
    ->setPagination()
    ->getCollection();

$query = new ModelQueryBuilder($params);
$collection = $service->getModels($query);

use Sergyjar\QueryBuilder\Contracts\QueryBuilderInterface;

public function getModels(QueryBuilderInterface $queryBuilder): Collection
{
    return = $queryBuilder
        ->setFilters()
        ->setSort()
        ->setPagination()
        ->getCollection();
}

'sort_key' => 'sort',
'order_key' => 'order',

'sort_default' => 'id',
'order_default' => 'asc',

namespace App\Path\For\File;

use App\Models\Model;
use Sergyjar\QueryBuilder\AbstractQueryBuilder;
use Sergyjar\QueryBuilder\Enums\SortDirection

class ModelQueryBuilder extends AbstractQueryBuilder
{
	protected string $sortKey = 'customSortKey';
	protected string $orderKey = 'customOrderKey';
	protected string $sortDefault = 'custom_sort_model_field';
	protected string $orderDefault = SortDirection::DESC;
...

'page' => 'page',
'per_page' => 'perPage',

'page_default' => 1,
'per_page_default' => 20,

namespace App\Path\For\File;

use App\Models\Model;
use Sergyjar\QueryBuilder\AbstractQueryBuilder;

class ModelQueryBuilder extends AbstractQueryBuilder
{
	protected string $pageKey = 'customPageKey';
	protected string $perPageKey = 'customPerPageKey';
	protected int $pageDefault = 2;
	protected int $perPageDefault = 3;
...

$query->withTrashed()

$query->setSelect($select)

$pagination = $query->getPagination();

[
    'page' => 20,
    'perPage' => 1,
    'total' => 12,
    'totalPages' => 15,
]
bash
php artisan vendor:publish --provider="Sergyjar\QueryBuilder\Providers\QueryBuilderServiceProvider"

php artisan query-builder:make ModelName