81 lines
2.7 KiB
PHP
81 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Admin;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\Category;
|
|
use App\Models\Product;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\View\View;
|
|
|
|
class ProductController extends Controller
|
|
{
|
|
public function index(): View
|
|
{
|
|
$products = Product::with('category')->orderBy('sort')->orderBy('name')->paginate(20);
|
|
|
|
return view('admin.products.index', compact('products'));
|
|
}
|
|
|
|
public function create(): View
|
|
{
|
|
$categories = Category::ofType('product')->orderBy('sort')->orderBy('name')->get();
|
|
|
|
return view('admin.products.form', ['product' => null, 'categories' => $categories]);
|
|
}
|
|
|
|
public function store(Request $request)
|
|
{
|
|
$data = $request->validate([
|
|
'category_id' => ['nullable', 'exists:categories,id'],
|
|
'name' => ['required', 'string', 'max:120'],
|
|
'slug' => ['required', 'string', 'max:120', 'unique:products,slug'],
|
|
'model' => ['nullable', 'string', 'max:60'],
|
|
'summary' => ['nullable', 'string', 'max:255'],
|
|
'description' => ['nullable', 'string'],
|
|
'specs' => ['nullable', 'string'],
|
|
'cover' => ['nullable', 'string', 'max:255'],
|
|
'status' => ['required', 'in:published,draft'],
|
|
'sort' => ['integer'],
|
|
]);
|
|
|
|
Product::create($data);
|
|
|
|
return redirect()->route('admin.products.index')->with('success', '产品已创建');
|
|
}
|
|
|
|
public function edit(Product $product): View
|
|
{
|
|
$categories = Category::ofType('product')->orderBy('sort')->orderBy('name')->get();
|
|
|
|
return view('admin.products.form', compact('product', 'categories'));
|
|
}
|
|
|
|
public function update(Request $request, Product $product)
|
|
{
|
|
$data = $request->validate([
|
|
'category_id' => ['nullable', 'exists:categories,id'],
|
|
'name' => ['required', 'string', 'max:120'],
|
|
'slug' => ['required', 'string', 'max:120', 'unique:products,slug,' . $product->id],
|
|
'model' => ['nullable', 'string', 'max:60'],
|
|
'summary' => ['nullable', 'string', 'max:255'],
|
|
'description' => ['nullable', 'string'],
|
|
'specs' => ['nullable', 'string'],
|
|
'cover' => ['nullable', 'string', 'max:255'],
|
|
'status' => ['required', 'in:published,draft'],
|
|
'sort' => ['integer'],
|
|
]);
|
|
|
|
$product->update($data);
|
|
|
|
return redirect()->route('admin.products.index')->with('success', '产品已更新');
|
|
}
|
|
|
|
public function destroy(Product $product)
|
|
{
|
|
$product->delete();
|
|
|
|
return redirect()->route('admin.products.index')->with('success', '产品已删除');
|
|
}
|
|
}
|