1. Go to this page and download the library: Download youcanshop/queryoption 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/ */
youcanshop / queryoption example snippets
class ListUsersController as Controller
{
private UserService $userService;
public function __construct(UserService $userService) {
$this->userService = $userService;
}
public function __invoke(Request $request) {
$queryOption = QueryOptionFactory::createFromIlluminateRequest($request);
$this->userService->paginate($queryOption);
}
}
use YouCanShop\QueryOption\Laravel\UsesQueryOption;
class PostRepository {
use UsesQueryOption;
public function paginated(QueryOption $queryOption)
{
$query = Post::query();
[$query, $queryOption] = $this->pipeThroughCriterias($query, $queryOption);
return $query->paginate(
$queryOption->getLimit(),
'*',
'page',
$queryOption->getPage()
);
}
protected function getQueryOptionCriterias(): array
{
return [
SearchCriteria::class,
FilterByPublishedAtCriteria::class,
SortByCriteria::class
];
}
}
class SearchCriteria
{
public function handle(array $data, Closure $next)
{
[$query, $queryOption] = $data;
$search = $queryOption->getSearch();
if (!empty($search->getTerm())) {
if ($search->getType() === 'like') {
$query->where('title', 'like', "%" . $search->getTerm() . "%");
}
if ($search->getType() === 'equal') {
$query->where('title', '=', $search->getTerm());
}
}
return $next([$query, $queryOption]);
}
}
class SortByCriteria
{
public function handle(array $data, Closure $next)
{
[$query, $queryOption] = $data;
$sort = $queryOption->getSort();
// allow sorting only by publish date and title
if(!in_array($sort->getField(), ['published_date','title'])) {
return $next([$query, $queryOption]);
}
$query->orderBy($sort->getField(), $sort->getDirection());
return $next([$query, $queryOption]);
}
}
class FilterByPublishedAtCriteria
{
public function handle(array $data, Closure $next)
{
[$query, $queryOption] = $data;
$filter = $queryOption->getFilters()->findByName('publish_date');
$creationDate = Carbon::parse($filter->getValue());
$query->whereDate('published_at', $filter->getOperator(), $creationDate);
return $next([$query, $queryOption]);
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.