98 lines
2.7 KiB
PHP
98 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Admin;
|
|
|
|
use App\Http\Controllers\Concerns\ParsesDataTableQuery;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Http\Requests\Admin\CategoryRequest;
|
|
use App\Models\Category;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Http\RedirectResponse;
|
|
use Illuminate\Http\Request;
|
|
use Inertia\Inertia;
|
|
use Inertia\Response;
|
|
|
|
class CategoryController extends Controller
|
|
{
|
|
use ParsesDataTableQuery;
|
|
|
|
public function index(Request $request): Response
|
|
{
|
|
$tableQuery = $this->parseDataTableQuery($request);
|
|
$search = $tableQuery['search'];
|
|
$sort = $tableQuery['sort'];
|
|
$direction = $tableQuery['direction'];
|
|
|
|
$query = Category::query()
|
|
->when($search !== '', function (Builder $query) use ($search): void {
|
|
$query->where(function (Builder $query) use ($search): void {
|
|
$query->where('name', 'like', "%{$search}%");
|
|
});
|
|
});
|
|
|
|
$this->applySorting($query, $sort, $direction);
|
|
|
|
$categories = $query
|
|
->paginate(10)
|
|
->withQueryString()
|
|
->through(fn (Category $category) => $this->transformCategory($category));
|
|
|
|
return Inertia::render('admin/categories/Index', [
|
|
'categories' => $categories,
|
|
'filters' => $this->dataTableFilters($tableQuery),
|
|
]);
|
|
}
|
|
|
|
public function store(CategoryRequest $request): RedirectResponse
|
|
{
|
|
Category::create($request->validated());
|
|
|
|
Inertia::flash('success', 'Kategori berhasil ditambahkan.');
|
|
|
|
return redirect()->route('admin.master.categories.index');
|
|
}
|
|
|
|
public function update(CategoryRequest $request, Category $category): RedirectResponse
|
|
{
|
|
$validated = $request->validated();
|
|
$category->name = $validated['name'];
|
|
$category->save();
|
|
|
|
Inertia::flash('success', 'Kategori berhasil diperbarui.');
|
|
|
|
return redirect()->route('admin.master.categories.index');
|
|
}
|
|
|
|
public function destroy(Category $category): RedirectResponse
|
|
{
|
|
$category->delete();
|
|
|
|
Inertia::flash('success', 'Kategori berhasil dihapus.');
|
|
|
|
return redirect()->route('admin.master.categories.index');
|
|
}
|
|
|
|
private function applySorting(Builder $query, string $sort, string $direction): void
|
|
{
|
|
if (in_array($sort, ['name', 'slug'], true)) {
|
|
$query->orderBy($sort, $direction);
|
|
|
|
return;
|
|
}
|
|
|
|
$query->latest();
|
|
}
|
|
|
|
/**
|
|
* @return array<string, mixed>
|
|
*/
|
|
private function transformCategory(Category $category): array
|
|
{
|
|
return [
|
|
'id' => $category->id,
|
|
'name' => $category->name,
|
|
'slug' => $category->slug,
|
|
];
|
|
}
|
|
}
|