76 lines
2.2 KiB
PHP
76 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Master;
|
|
|
|
use App\Models\Supplier;
|
|
use App\Services\Concerns\CachesQuery;
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
|
|
class SupplierService
|
|
{
|
|
use CachesQuery;
|
|
|
|
public function paginateForIndex(array $tableQuery): LengthAwarePaginator
|
|
{
|
|
$query = Supplier::query()
|
|
->when($tableQuery['search'] !== '', function (Builder $query) use ($tableQuery): void {
|
|
$search = $tableQuery['search'];
|
|
$query->where(function (Builder $query) use ($search): void {
|
|
$query->where('name', 'like', "%{$search}%")
|
|
->orWhere('phone_number', 'like', "%{$search}%")
|
|
->orWhere('address', 'like', "%{$search}%");
|
|
});
|
|
});
|
|
|
|
$this->applySorting($query, $tableQuery['sort'], $tableQuery['direction']);
|
|
|
|
return $query
|
|
->paginate(25)
|
|
->withQueryString();
|
|
}
|
|
|
|
public function create(array $validated): void
|
|
{
|
|
Supplier::create($validated);
|
|
$this->cacheForget('master:suppliers:options');
|
|
}
|
|
|
|
public function update(Supplier $supplier, array $validated): void
|
|
{
|
|
$supplier->update($validated);
|
|
$this->cacheForget('master:suppliers:options');
|
|
}
|
|
|
|
public function delete(Supplier $supplier): void
|
|
{
|
|
$supplier->delete();
|
|
$this->cacheForget('master:suppliers:options');
|
|
}
|
|
|
|
public function getSelectOptions(): array
|
|
{
|
|
return $this->cacheRemember('master:suppliers:options', 3600, function () {
|
|
return Supplier::query()
|
|
->orderBy('name')
|
|
->get(['id', 'name'])
|
|
->map(fn (Supplier $supplier) => [
|
|
'value' => $supplier->id,
|
|
'label' => $supplier->name,
|
|
])
|
|
->all();
|
|
});
|
|
}
|
|
|
|
private function applySorting(Builder $query, string $sort, string $direction): void
|
|
{
|
|
if (in_array($sort, ['name', 'phone_number', 'address'], true)) {
|
|
$query->orderBy($sort, $direction);
|
|
|
|
return;
|
|
}
|
|
|
|
$query->latest();
|
|
}
|
|
}
|