84 lines
2.4 KiB
PHP
84 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Master;
|
|
|
|
use App\Models\Customer;
|
|
use App\Services\Concerns\CachesQuery;
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
|
|
class CustomerService
|
|
{
|
|
use CachesQuery;
|
|
|
|
public function paginateForIndex(array $tableQuery): LengthAwarePaginator
|
|
{
|
|
$query = Customer::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
|
|
{
|
|
Customer::create($validated);
|
|
$this->cacheForget('master:customers:options');
|
|
}
|
|
|
|
public function createAndReturn(array $validated): Customer
|
|
{
|
|
$customer = Customer::create($validated);
|
|
$this->cacheForget('master:customers:options');
|
|
|
|
return $customer;
|
|
}
|
|
|
|
public function update(Customer $customer, array $validated): void
|
|
{
|
|
$customer->update($validated);
|
|
$this->cacheForget('master:customers:options');
|
|
}
|
|
|
|
public function delete(Customer $customer): void
|
|
{
|
|
$customer->delete();
|
|
$this->cacheForget('master:customers:options');
|
|
}
|
|
|
|
public function getSelectOptions(): array
|
|
{
|
|
return $this->cacheRemember('master:customers:options', 3600, function () {
|
|
return Customer::query()
|
|
->orderBy('name')
|
|
->get(['id', 'name'])
|
|
->map(fn (Customer $customer) => [
|
|
'value' => $customer->id,
|
|
'label' => $customer->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();
|
|
}
|
|
}
|