
中級者向けです。
ハンズオン的な記事ではありません。
すみません🐱
もくじ
API例
http://yuu3.example.net/console/api/v2/staff_management/list?limit=1&offset=1&sort_key=id&sort_type=desc&year=2021&month=08
SampleService
/**
* リスト取得
*
* @param array $params
*/
public function list(array $params)
{
$params['company_id'] = $this->getCompanyId();
$rows = $this->r_staff->getList($params);
return [
"total" => $rows->count(),
"rows" => $rows,
"headers" => config('system.STAFF_LIST_HEADERS'),
];
}
StaffRepository
<?php
namespace App\Repositories\Staff;
use App\Entities\Staff;
use App\Repositories\Traits\ResourceConstructTrait;
use App\Repositories\AbstractRepository;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class StaffRepository extends AbstractRepository
{
use ResourceConstructTrait;
const LIST_DEFAULT_LIMIT = 5;
private $_list_filter_params = [
"limit",
"offset",
"sort_key",
"sort_type",
];
private $_where_filter_params = [
"year",
"month",
];
public function __construct(Staff $resource)
{
$this->resource = $resource;
}
public function getList(array $params, bool $is_all = false)
{
$list_filter_params = Arr::only($params, $this->_list_filter_params);
$where_filter_params = Arr::only($params, $this->_where_filter_params);
$query = $this->resource->query();
$query->where('company_id', $params['company_id']);
// 全件取得の場合、limit,offsetは確認しない
if (!$is_all) {
// 件数
if (isset($list_filter_params["limit"]) && preg_match('/^[0-9]+$/', $list_filter_params["limit"])) {
$query->limit($list_filter_params["limit"]);
} else {
$query->limit(self::LIST_DEFAULT_LIMIT);
}
// 開始位置
if (isset($list_filter_params["offset"]) && preg_match('/^[0-9]+$/', $list_filter_params["offset"])) {
$query->offset($list_filter_params["offset"]);
}
}
// ソートキーが存在しない場合はIDがソートキーとなる、ソートタイプがない場合はasc
$sort_key = isset($list_filter_params["sort_key"]) && in_array($list_filter_params["sort_key"], $list_filter_params) ? $list_filter_params["sort_key"] : 'id';
$sort_type = isset($list_filter_params["sort_type"]) && in_array($list_filter_params["sort_type"], ['asc', 'desc']) ? $list_filter_params["sort_type"] : 'asc';
$query->orderBy($sort_key, $sort_type);
// 年 yyyy
if (isset($where_filter_params["year"]) && preg_match('/^([1-9][0-9]{3})$/', $where_filter_params['year'])) {
$query->whereYear('reserve_date', $where_filter_params['year']);
}
// 月 month
// ex1. 1
// ex2. 01
// ex3. 12
if (isset($where_filter_params["month"]) && preg_match('/^(0[1-9]{1}|[1-9]{1}|1[0-2]{1})$/', $where_filter_params['month'])) {
$query->whereMonth('reserve_date', $where_filter_params['month']);
}
return $query->get();
}
}

