tsett
This commit is contained in:
122
app/Http/Controllers/Admin/BrandsController.php
Normal file
122
app/Http/Controllers/Admin/BrandsController.php
Normal file
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Brand;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
use function Avifinfo\read;
|
||||
|
||||
class BrandsController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$brands = Brand::orderBy('name')->paginate(5);
|
||||
return view('admin.brands.brands', compact('brands'));
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:255|unique:brands',
|
||||
'description' => 'nullable|string',
|
||||
'logo' => 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048',
|
||||
'website' => 'nullable|url|max:255',
|
||||
'country' => 'nullable|string|max:100',
|
||||
'is_active' => 'nullable|boolean',
|
||||
], [
|
||||
'name.required' => 'Название бренда обязательно',
|
||||
'name.unique' => 'Бренд с таким названием уже существует',
|
||||
'name.max' => 'Название не может быть длиннее 255 символов',
|
||||
'logo.image' => 'Загрузите изображение (jpg, png, svg)',
|
||||
'logo.max' => 'Изображение не должно превышать 2 МБ',
|
||||
'website.url' => 'Введите корректный URL сайта',
|
||||
'website.max' => 'URL сайта не может быть длиннее 255 символов',
|
||||
'country.max' => 'Название страны не может быть длиннее 100 символов',
|
||||
]);
|
||||
|
||||
if ($request->hasFile('logo')) {
|
||||
$logo = $request->file('logo');
|
||||
$logoName = Str::slug($request->name) . '.' . $logo->getClientOriginalExtension();
|
||||
$logo->move(public_path('assets/images/brands'), $logoName);
|
||||
$validated['logo'] = $logoName;
|
||||
}
|
||||
|
||||
$validated['slug'] = Str::slug($request->name);
|
||||
|
||||
$validated['is_active'] = $request->has('is_active');
|
||||
|
||||
Brand::create($validated);
|
||||
|
||||
return redirect()->route('admin.brands')
|
||||
->with('success', 'Бренд "' . $request->name . '" успешно создан');
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
$brand = Brand::findOrFail($id);
|
||||
return view('admin.brands.edit', compact('brand'));
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$brand = Brand::findOrFail($id);
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'description' => 'nullable|string',
|
||||
'logo' => 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048',
|
||||
'website' => 'nullable|url|max:255',
|
||||
'country' => 'nullable|string|max:100',
|
||||
'is_active' => 'nullable|boolean',
|
||||
], [
|
||||
'name.required' => 'Название бренда обязательно',
|
||||
'name.max' => 'Название не может быть длиннее 255 символов',
|
||||
'logo.image' => 'Загрузите изображение (jpg, png, svg)',
|
||||
'logo.mimes' => 'Изображение должно быть в форматах: jpg, jpeg, png, svg',
|
||||
'logo.max' => 'Изображение не должно превышать 2 МБ',
|
||||
'website.url' => 'Введите корректный URL сайта',
|
||||
'website.max' => 'URL сайта не может быть длиннее 255 символов',
|
||||
'country.max' => 'Название страны не может быть длиннее 100 символов',
|
||||
]);
|
||||
|
||||
$brand->name = $validated['name'];
|
||||
$brand->description = $validated['description'];
|
||||
$brand->website = $validated['website'];
|
||||
$brand->country = $validated['country'];
|
||||
$brand->is_active = $request->has('is_active');
|
||||
|
||||
if ($request->hasFile('logo')) {
|
||||
if ($brand->logo && file_exists(public_path('assets/images/brands/' . $brand->logo))) {
|
||||
unlink(public_path('assets/images/brands/' . $brand->logo));
|
||||
}
|
||||
|
||||
$logo = $request->file('logo');
|
||||
$logoName = Str::slug($request->name) . '.' . $logo->getClientOriginalExtension();
|
||||
$logo->move(public_path('assets/images/brands'), $logoName);
|
||||
$brand->logo = $logoName;
|
||||
}
|
||||
|
||||
$brand->save();
|
||||
|
||||
return redirect()->route('admin.brands')
|
||||
->with('success', 'Бренд "' . $brand->name . '" успешно обновлен');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$brand = Brand::findOrFail($id);
|
||||
|
||||
$brandName = $brand->name;
|
||||
|
||||
if ($brand->logo && file_exists(public_path('assets/images/brands/' . $brand->logo))) {
|
||||
unlink(public_path('assets/images/brands/' . $brand->logo));
|
||||
}
|
||||
|
||||
$brand->delete();
|
||||
|
||||
return redirect()->route('admin.brands')->with('success', 'Бренд "' . $brandName . '" успешно удален');
|
||||
}
|
||||
}
|
||||
217
app/Http/Controllers/Admin/CategoriesController.php
Normal file
217
app/Http/Controllers/Admin/CategoriesController.php
Normal file
@@ -0,0 +1,217 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Category;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class CategoriesController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$categories = Category::getFlatTree();
|
||||
|
||||
$allCategories = Category::getSelectTree(2);
|
||||
|
||||
return view('admin.categories.categories', compact('categories', 'allCategories'));
|
||||
}
|
||||
|
||||
public function moveUp($id)
|
||||
{
|
||||
$category = Category::findOrFail($id);
|
||||
|
||||
$previous = Category::where('parent_id', $category->parent_id)
|
||||
->where('sort_order', '<', $category->sort_order)
|
||||
->orderBy('sort_order', 'desc')
|
||||
->first();
|
||||
|
||||
if ($previous) {
|
||||
$temp = $category->sort_order;
|
||||
$category->sort_order = $previous->sort_order;
|
||||
$previous->sort_order = $temp;
|
||||
|
||||
$category->save();
|
||||
$previous->save();
|
||||
}
|
||||
|
||||
return redirect()->route('admin.categories')->with('success', 'Порядок категорий обновлен');
|
||||
}
|
||||
|
||||
public function moveDown($id)
|
||||
{
|
||||
$category = Category::findOrFail($id);
|
||||
|
||||
$next = Category::where('parent_id', $category->parent_id)
|
||||
->where('sort_order', '>', $category->sort_order)
|
||||
->orderBy('sort_order', 'asc')
|
||||
->first();
|
||||
|
||||
if ($next) {
|
||||
$temp = $category->sort_order;
|
||||
$category->sort_order = $next->sort_order;
|
||||
$next->sort_order = $temp;
|
||||
|
||||
$category->save();
|
||||
$next->save();
|
||||
}
|
||||
|
||||
return redirect()->route('admin.categories')->with('success', 'Порядок категорий обновлен');
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'parent_id' => 'nullable|exists:categories,id',
|
||||
'name' => 'required|string|max:255',
|
||||
'description' => 'nullable|string',
|
||||
'icon' => 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048',
|
||||
'image' => 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048',
|
||||
'is_active' => 'nullable|boolean',
|
||||
], [
|
||||
'name.required' => 'Название категории обязательно',
|
||||
'name.max' => 'Название не может быть длиннее 255 символов',
|
||||
'icon.image' => 'Загрузите изображение (jpg, png, svg)',
|
||||
'icon.max' => 'Изображение не должно превышать 2 МБ',
|
||||
'image.image' => 'Загрузите изображение (jpg, png, svg)',
|
||||
'image.max' => 'Изображение не должно превышать 2 МБ',
|
||||
'parent_id.exists' => 'Выбранная родительская категория не существует',
|
||||
]);
|
||||
|
||||
if ($request->hasFile('icon')) {
|
||||
$icon = $request->file('icon');
|
||||
$iconName = Str::slug($request->name) . '_icon.' . $icon->getClientOriginalExtension();
|
||||
$icon->move(public_path('assets/images/categories/icons'), $iconName);
|
||||
$validated['icon'] = $iconName;
|
||||
}
|
||||
|
||||
if ($request->hasFile('image')) {
|
||||
$image = $request->file('image');
|
||||
$imageName = Str::slug($request->name) . '_image.' . $image->getClientOriginalExtension();
|
||||
$image->move(public_path('assets/images/categories/images'), $imageName);
|
||||
$validated['image'] = $imageName;
|
||||
}
|
||||
|
||||
$validated['slug'] = Str::slug($request->name);
|
||||
|
||||
if (Category::where('slug', $validated['slug'])->exists()) {
|
||||
$validated['slug'] = $validated['slug'] . '-' . uniqid();
|
||||
}
|
||||
|
||||
$validated['is_active'] = $request->has('is_active');
|
||||
$validated['sort_order'] = Category::where('parent_id', $request->parent_id)->max('sort_order') + 10;
|
||||
|
||||
Category::create($validated);
|
||||
|
||||
return redirect()->route('admin.categories')
|
||||
->with('success', 'Категория "' . $request->name . '" успешно создана');
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
$category = Category::findOrFail($id);
|
||||
|
||||
$allCategories = Category::with('parent')
|
||||
->get()
|
||||
->map(function ($cat) use ($category) {
|
||||
$cat->level = $cat->calculateLevel();
|
||||
$cat->disabled = $cat->id == $category->id || $cat->isDescendantOf($category->id);
|
||||
return $cat;
|
||||
})
|
||||
->filter(function ($cat) {
|
||||
return $cat->level < 2;
|
||||
});
|
||||
|
||||
return view('admin.categories.edit', compact('category', 'allCategories'));
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$category = Category::findOrFail($id);
|
||||
|
||||
$validated = $request->validate([
|
||||
'parent_id' => 'nullable|exists:categories,id',
|
||||
'name' => 'required|string|max:255',
|
||||
'description' => 'nullable|string',
|
||||
'icon' => 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048',
|
||||
'image' => 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048',
|
||||
'is_active' => 'nullable|boolean',
|
||||
'remove_icon' => 'nullable|boolean',
|
||||
'remove_image' => 'nullable|boolean',
|
||||
], [
|
||||
'name.required' => 'Название категории обязательно',
|
||||
'name.max' => 'Название не может быть длиннее 255 символов',
|
||||
'icon.image' => 'Загрузите изображение (jpg, png, svg)',
|
||||
'icon.max' => 'Изображение не должно превышать 2 МБ',
|
||||
'image.image' => 'Загрузите изображение (jpg, png, svg)',
|
||||
'image.max' => 'Изображение не должно превышать 2 МБ',
|
||||
'parent_id.exists' => 'Выбранная родительская категория не существует',
|
||||
]);
|
||||
|
||||
$category->name = $validated['name'];
|
||||
$category->description = $validated['description'];
|
||||
$category->parent_id = $validated['parent_id'];
|
||||
$category->is_active = $request->has('is_active');
|
||||
|
||||
if ($request->hasFile('icon')) {
|
||||
if ($category->icon && file_exists(public_path('assets/images/categories/icons/' . $category->icon))) {
|
||||
unlink(public_path('assets/images/categories/icons/' . $category->icon));
|
||||
}
|
||||
|
||||
$icon = $request->file('icon');
|
||||
$iconName = Str::slug($request->name) . '_icon.' . $icon->getClientOriginalExtension();
|
||||
$icon->move(public_path('assets/images/categories/icons'), $iconName);
|
||||
$category->icon = $iconName;
|
||||
}
|
||||
|
||||
if ($request->has('remove_icon') && $request->remove_icon == 1) {
|
||||
if ($category->icon && file_exists(public_path('assets/images/categories/icons/' . $category->icon))) {
|
||||
unlink(public_path('assets/images/categories/icons/' . $category->icon));
|
||||
}
|
||||
$category->icon = null;
|
||||
}
|
||||
|
||||
if ($request->hasFile('image')) {
|
||||
if ($category->image && file_exists(public_path('assets/images/categories/images/' . $category->image))) {
|
||||
unlink(public_path('assets/images/categories/images/' . $category->image));
|
||||
}
|
||||
|
||||
$image = $request->file('image');
|
||||
$imageName = Str::slug($request->name) . '_image.' . $image->getClientOriginalExtension();
|
||||
$image->move(public_path('assets/images/categories/images'), $imageName);
|
||||
$category->image = $imageName;
|
||||
}
|
||||
|
||||
if ($request->has('remove_image') && $request->remove_image == 1) {
|
||||
if ($category->image && file_exists(public_path('assets/images/categories/images/' . $category->image))) {
|
||||
unlink(public_path('assets/images/categories/images/' . $category->image));
|
||||
}
|
||||
$category->image = null;
|
||||
}
|
||||
|
||||
$category->save();
|
||||
|
||||
return redirect()->route('admin.categories')
|
||||
->with('success', 'Категория "' . $category->name . '" успешно обновлена');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$category = Category::findOrFail($id);
|
||||
$categoryName = $category->name;
|
||||
|
||||
if ($category->icon && file_exists(public_path('assets/images/categories/icons/' . $category->icon))) {
|
||||
unlink(public_path('assets/images/categories/icons/' . $category->icon));
|
||||
}
|
||||
|
||||
if ($category->image && file_exists(public_path('assets/images/categories/images/' . $category->image))) {
|
||||
unlink(public_path('assets/images/categories/images/' . $category->image));
|
||||
}
|
||||
|
||||
$category->delete();
|
||||
|
||||
return redirect()->route('admin.categories')
|
||||
->with('success', 'Категория "' . $categoryName . '" успешно удалена');
|
||||
}
|
||||
}
|
||||
90
app/Http/Controllers/Admin/ContactController.php
Normal file
90
app/Http/Controllers/Admin/ContactController.php
Normal file
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Contact;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class ContactController extends Controller
|
||||
{
|
||||
public function edit()
|
||||
{
|
||||
$contact = Contact::first();
|
||||
|
||||
if (!$contact) {
|
||||
$contact = Contact::create([
|
||||
'name' => 'Хвостики и лапки'
|
||||
]);
|
||||
}
|
||||
|
||||
return view('admin.contacts.edit', compact('contact'));
|
||||
}
|
||||
|
||||
public function update(Request $request)
|
||||
{
|
||||
$contact = Contact::first();
|
||||
|
||||
if (!$contact) {
|
||||
$contact = Contact::create();
|
||||
}
|
||||
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'description' => 'nullable|string|max:255',
|
||||
'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
|
||||
'favicon' => 'nullable|image|mimes:ico,png,svg|max:1024',
|
||||
'phone' => 'nullable|string|max:255',
|
||||
'email' => 'nullable|email|max:255',
|
||||
'address' => 'nullable|string|max:255',
|
||||
'work_hours' => 'nullable|string|max:255',
|
||||
'telegram' => 'nullable|string|max:255',
|
||||
'whatsapp' => 'nullable|string|max:255',
|
||||
'vkontakte' => 'nullable|string|max:255',
|
||||
'meta_title' => 'nullable|string|max:255',
|
||||
'meta_description' => 'nullable|string',
|
||||
'meta_keywords' => 'nullable|string'
|
||||
]);
|
||||
|
||||
if ($request->hasFile('logo')) {
|
||||
if ($contact->logo && file_exists(public_path('assets/images/logo/' . $contact->logo))) {
|
||||
unlink(public_path('assets/images/logo/' . $contact->logo));
|
||||
}
|
||||
|
||||
$logoFile = $request->file('logo');
|
||||
$logoName = time() . '_logo.' . $logoFile->getClientOriginalExtension();
|
||||
$logoFile->move(public_path('assets/images/logo'), $logoName);
|
||||
$contact->logo = $logoName;
|
||||
}
|
||||
|
||||
if ($request->hasFile('favicon')) {
|
||||
if ($contact->favicon && file_exists(public_path('assets/images/logo/' . $contact->favicon))) {
|
||||
unlink(public_path('assets/images/logo/' . $contact->favicon));
|
||||
}
|
||||
|
||||
$faviconFile = $request->file('favicon');
|
||||
$faviconName = time() . '_favicon.' . $faviconFile->getClientOriginalExtension();
|
||||
$faviconFile->move(public_path('assets/images/logo'), $faviconName);
|
||||
$contact->favicon = $faviconName;
|
||||
}
|
||||
|
||||
$contact->update([
|
||||
'name' => $request->name,
|
||||
'description' => $request->description,
|
||||
'phone' => $request->phone,
|
||||
'email' => $request->email,
|
||||
'address' => $request->address,
|
||||
'work_hours' => $request->work_hours,
|
||||
'telegram' => $request->telegram,
|
||||
'whatsapp' => $request->whatsapp,
|
||||
'vkontakte' => $request->vkontakte,
|
||||
'meta_title' => $request->meta_title,
|
||||
'meta_description' => $request->meta_description,
|
||||
'meta_keywords' => $request->meta_keywords
|
||||
]);
|
||||
|
||||
return redirect()->route('admin.contacts.edit')
|
||||
->with('success', 'Данные сайта успешно обновлены');
|
||||
}
|
||||
}
|
||||
31
app/Http/Controllers/Admin/DashboardController.php
Normal file
31
app/Http/Controllers/Admin/DashboardController.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Product;
|
||||
use App\Models\Order;
|
||||
use App\Models\OrderItem;
|
||||
use App\Models\ProductVariation;
|
||||
use App\Models\User;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$data = [
|
||||
'totalUsers' => User::count(),
|
||||
'totalProducts' => ProductVariation::count(),
|
||||
'totalOrders' => Order::count(),
|
||||
'recentOrders' => Order::with('user')
|
||||
->orderBy('created_at', 'desc')
|
||||
->limit(5)
|
||||
->get(),
|
||||
'popularProducts' => OrderItem::popular(10)->get(),
|
||||
'monthlyRevenue' => Order::getMonthlyRevenue(),
|
||||
|
||||
];
|
||||
return view('admin.dashboard', $data);
|
||||
}
|
||||
}
|
||||
61
app/Http/Controllers/Admin/OrdersController.php
Normal file
61
app/Http/Controllers/Admin/OrdersController.php
Normal file
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Order;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class OrdersController extends Controller
|
||||
{
|
||||
/**
|
||||
* Список заказов
|
||||
*/
|
||||
public function index(Request $request)
|
||||
{
|
||||
$query = Order::with('user');
|
||||
|
||||
// Поиск по номеру заказа
|
||||
if ($request->filled('search')) {
|
||||
$query->where('order_number', 'like', "%{$request->search}%");
|
||||
}
|
||||
|
||||
// Фильтр по статусу
|
||||
if ($request->filled('status')) {
|
||||
$query->where('delivery_status', $request->status);
|
||||
}
|
||||
|
||||
$orders = $query->orderBy('created_at', 'desc')->paginate(20);
|
||||
|
||||
return view('admin.orders.orders', compact('orders'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Детали заказа
|
||||
*/
|
||||
public function show($id)
|
||||
{
|
||||
$order = Order::with(['user', 'items.variation.product'])->findOrFail($id);
|
||||
return view('admin.orders.show', compact('order'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновление статуса заказа
|
||||
*/
|
||||
public function updateStatus(Request $request, $id)
|
||||
{
|
||||
$request->validate([
|
||||
'delivery_status' => 'required|in:pending,processing,shipped,delivered,cancelled',
|
||||
'payment_status' => 'required|in:pending,paid,failed'
|
||||
]);
|
||||
|
||||
$order = Order::findOrFail($id);
|
||||
$order->update([
|
||||
'delivery_status' => $request->delivery_status,
|
||||
'payment_status' => $request->payment_status
|
||||
]);
|
||||
|
||||
return redirect()->route('admin.orders.show', $order->id)
|
||||
->with('success', 'Статус заказа обновлен');
|
||||
}
|
||||
}
|
||||
107
app/Http/Controllers/Admin/PermissionsController.php
Normal file
107
app/Http/Controllers/Admin/PermissionsController.php
Normal file
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class PermissionsController extends Controller
|
||||
{
|
||||
/**
|
||||
* Список прав
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$permissions = Permission::orderBy('group')->orderBy('name')->paginate(10);
|
||||
return view('admin.permissions.permissions', compact('permissions'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохранить новое право
|
||||
*/
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255|unique:permissions',
|
||||
'slug' => 'required|string|max:255|unique:permissions',
|
||||
'group' => 'nullable|string|max:255',
|
||||
'description' => 'nullable|string'
|
||||
], [
|
||||
'name.required' => 'Обязательно для заполнения',
|
||||
'name.unique' => 'Право с таким названием уже существует',
|
||||
'slug.required' => 'Обязательно для заполнения',
|
||||
'slug.unique' => 'Право с таким slug уже существует'
|
||||
]);
|
||||
|
||||
Permission::create([
|
||||
'name' => $request->name,
|
||||
'slug' => $request->slug,
|
||||
'group' => $request->group,
|
||||
'description' => $request->description
|
||||
]);
|
||||
|
||||
return redirect()->route('admin.permissions')
|
||||
->with('success', 'Право "' . $request->name . '" успешно создано');
|
||||
}
|
||||
|
||||
/**
|
||||
* Форма редактирования
|
||||
*/
|
||||
public function edit($id)
|
||||
{
|
||||
$permission = Permission::findOrFail($id);
|
||||
return view('admin.permissions.edit', compact('permission'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновить право
|
||||
*/
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$permission = Permission::findOrFail($id);
|
||||
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255|unique:permissions,name,' . $id,
|
||||
'slug' => 'required|string|max:255|unique:permissions,slug,' . $id,
|
||||
'group' => 'nullable|string|max:255',
|
||||
'description' => 'nullable|string'
|
||||
], [
|
||||
'name.required' => 'Обязательно для заполнения',
|
||||
'name.unique' => 'Право с таким названием уже существует',
|
||||
'slug.required' => 'Обязательно для заполнения',
|
||||
'slug.unique' => 'Право с таким slug уже существует'
|
||||
]);
|
||||
|
||||
$permission->update([
|
||||
'name' => $request->name,
|
||||
'slug' => $request->slug,
|
||||
'group' => $request->group,
|
||||
'description' => $request->description
|
||||
]);
|
||||
|
||||
return redirect()->route('admin.permissions')
|
||||
->with('success', 'Право "' . $permission->name . '" успешно обновлено');
|
||||
}
|
||||
|
||||
/**
|
||||
* Удалить право
|
||||
*/
|
||||
public function destroy($id)
|
||||
{
|
||||
$permission = Permission::findOrFail($id);
|
||||
|
||||
$rolesCount = $permission->roles()->count();
|
||||
|
||||
$permissionName = $permission->name;
|
||||
$permission->delete();
|
||||
|
||||
$message = 'Право "' . $permissionName . '" успешно удалено';
|
||||
if ($rolesCount > 0) {
|
||||
$message .= ' Право было удалено у ' . $rolesCount . ' ролей.';
|
||||
}
|
||||
|
||||
return redirect()->route('admin.permissions')
|
||||
->with('success', $message);
|
||||
}
|
||||
}
|
||||
722
app/Http/Controllers/Admin/ProductController.php
Normal file
722
app/Http/Controllers/Admin/ProductController.php
Normal file
@@ -0,0 +1,722 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductVariation;
|
||||
use App\Models\ProductAttribute;
|
||||
use App\Models\VariationAttribute;
|
||||
use App\Models\VariationImage;
|
||||
use App\Models\Category;
|
||||
use App\Models\Brand;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ProductController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$products = Product::with(['category', 'brand', 'variations.images'])
|
||||
->orderBy('created_at', 'desc')
|
||||
->paginate(15);
|
||||
|
||||
return view('admin.products.products', compact('products'));
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
$categories = Category::getFlatTree();
|
||||
$brands = Brand::active()->orderBy('name')->get();
|
||||
|
||||
return view('admin.products.create', compact('categories', 'brands'));
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'category_id' => 'required|exists:categories,id',
|
||||
'brand_id' => 'nullable|exists:brands,id',
|
||||
'description' => 'nullable|string',
|
||||
'is_active' => 'nullable|boolean',
|
||||
|
||||
'meta_title' => 'nullable|string|max:255',
|
||||
'meta_description' => 'nullable|string',
|
||||
'meta_keywords' => 'nullable|string',
|
||||
|
||||
'attributes' => 'nullable|array',
|
||||
'attributes.*.key' => 'nullable|string',
|
||||
'attributes.*.value' => 'nullable|string',
|
||||
|
||||
'variations' => 'required|array|min:1',
|
||||
'variations.*.name' => 'required|string|max:255',
|
||||
'variations.*.sku' => 'required|string|max:100|unique:product_variations,sku',
|
||||
'variations.*.price' => 'required|numeric|min:0',
|
||||
'variations.*.old_price' => 'nullable|numeric|min:0',
|
||||
'variations.*.stock' => 'required|integer|min:0',
|
||||
'variations.*.is_default' => 'nullable|boolean',
|
||||
'variations.*.attributes' => 'nullable|array',
|
||||
'variations.*.attributes.flavor' => 'nullable|string|max:100',
|
||||
'variations.*.attributes.color' => 'nullable|string|max:100',
|
||||
'variations.*.attributes.size' => 'nullable|string|max:50',
|
||||
'variations.*.attributes.weight' => 'nullable|numeric|min:0',
|
||||
|
||||
'variations.*.images' => 'nullable|array',
|
||||
'variations.*.images.*' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
|
||||
], [
|
||||
'name.required' => 'Название товара обязательно',
|
||||
'category_id.required' => 'Выберите категорию',
|
||||
'variations.required' => 'Добавьте хотя бы одну вариацию',
|
||||
'variations.*.name.required' => 'Название вариации обязательно',
|
||||
'variations.*.sku.required' => 'Артикул обязателен',
|
||||
'variations.*.sku.unique' => 'Артикул "{value}" уже существует',
|
||||
'variations.*.price.required' => 'Цена обязательна',
|
||||
'variations.*.stock.required' => 'Количество обязательно',
|
||||
'variations.*.images.*.image' => 'Файл должен быть изображением',
|
||||
'variations.*.images.*.mimes' => 'Допустимые форматы: jpg, jpeg, png, webp',
|
||||
'variations.*.images.*.max' => 'Размер изображения не должен превышать 2 МБ',
|
||||
]);
|
||||
|
||||
DB::beginTransaction();
|
||||
|
||||
try {
|
||||
$slug = Str::slug($request->name);
|
||||
$baseSlug = $slug;
|
||||
$counter = 1;
|
||||
while (Product::where('slug', $slug)->exists()) {
|
||||
$slug = $baseSlug . '-' . $counter;
|
||||
$counter++;
|
||||
}
|
||||
|
||||
$product = Product::create([
|
||||
'name' => $validated['name'],
|
||||
'slug' => $slug,
|
||||
'category_id' => $validated['category_id'],
|
||||
'brand_id' => $validated['brand_id'] ?? null,
|
||||
'description' => $validated['description'] ?? null,
|
||||
'is_active' => $request->boolean('is_active'),
|
||||
'meta_title' => $validated['meta_title'] ?? null,
|
||||
'meta_description' => $validated['meta_description'] ?? null,
|
||||
'meta_keywords' => $validated['meta_keywords'] ?? null,
|
||||
]);
|
||||
|
||||
// Сохраняем атрибуты товара
|
||||
if (!empty($validated['attributes'])) {
|
||||
foreach ($validated['attributes'] as $attr) {
|
||||
if (!empty($attr['key']) && !empty($attr['value'])) {
|
||||
ProductAttribute::create([
|
||||
'product_id' => $product->id,
|
||||
'key' => $attr['key'],
|
||||
'value' => $attr['value'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Создаем вариации
|
||||
foreach ($validated['variations'] as $index => $variationData) {
|
||||
$variation = ProductVariation::create([
|
||||
'product_id' => $product->id,
|
||||
'name' => $variationData['name'],
|
||||
'sku' => $variationData['sku'],
|
||||
'price' => $variationData['price'],
|
||||
'old_price' => $variationData['old_price'] ?? null,
|
||||
'stock' => $variationData['stock'],
|
||||
'is_default' => $variationData['is_default'] ?? ($index == 0),
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// Сохраняем атрибуты вариации
|
||||
if (!empty($variationData['attributes'])) {
|
||||
foreach ($variationData['attributes'] as $key => $value) {
|
||||
if (!empty($value) || $value === 0 || $value === '0') {
|
||||
VariationAttribute::create([
|
||||
'variation_id' => $variation->id,
|
||||
'key' => $key,
|
||||
'value' => $value,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Сохраняем изображения
|
||||
if ($request->hasFile("variations.{$index}.images")) {
|
||||
$files = $request->file("variations.{$index}.images");
|
||||
$validFiles = array_filter($files, function ($file) {
|
||||
return $file !== null && $file->isValid();
|
||||
});
|
||||
|
||||
if (!empty($validFiles)) {
|
||||
$this->saveVariationImages($validFiles, $product->slug, $variation->id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
|
||||
return redirect()->route('admin.products.create')
|
||||
->with('success', 'Товар "' . $product->name . '" успешно создан');
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
Log::error('Product create error: ' . $e->getMessage());
|
||||
return redirect()->back()
|
||||
->withInput()
|
||||
->with('error', 'Ошибка при создании товара: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
$product = Product::with(['variations.attributes', 'variations.images', 'attributes', 'brand', 'category'])->findOrFail($id);
|
||||
|
||||
$categories = Category::getFlatTree();
|
||||
|
||||
$brands = Brand::active()->orderBy('name')->get();
|
||||
|
||||
return view('admin.products.edit', compact('product', 'categories', 'brands'));
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$product = Product::findOrFail($id);
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'category_id' => 'required|exists:categories,id',
|
||||
'brand_id' => 'nullable|exists:brands,id',
|
||||
'description' => 'nullable|string',
|
||||
'is_active' => 'nullable|boolean',
|
||||
|
||||
'meta_title' => 'nullable|string|max:255',
|
||||
'meta_description' => 'nullable|string',
|
||||
'meta_keywords' => 'nullable|string',
|
||||
|
||||
'attributes' => 'nullable|array',
|
||||
'attributes.*.key' => 'nullable|string',
|
||||
'attributes.*.value' => 'nullable|string',
|
||||
|
||||
'variations' => 'required|array|min:1',
|
||||
'variations.*.id' => 'nullable|exists:product_variations,id',
|
||||
'variations.*.name' => 'required|string|max:255',
|
||||
'variations.*.sku' => 'required|string|max:100',
|
||||
'variations.*.price' => 'required|numeric|min:0',
|
||||
'variations.*.old_price' => 'nullable|numeric|min:0',
|
||||
'variations.*.stock' => 'required|integer|min:0',
|
||||
'variations.*.is_default' => 'nullable|boolean',
|
||||
'variations.*.attributes' => 'nullable|array',
|
||||
'variations.*.attributes.flavor' => 'nullable|string|max:100',
|
||||
'variations.*.attributes.color' => 'nullable|string|max:100',
|
||||
'variations.*.attributes.size' => 'nullable|string|max:50',
|
||||
'variations.*.attributes.weight' => 'nullable|numeric|min:0',
|
||||
|
||||
'variations.*.images' => 'nullable|array',
|
||||
'variations.*.images.*' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
|
||||
'variations.*.removed_images' => 'nullable|array',
|
||||
'variations.*.removed_images.*' => 'nullable|string',
|
||||
'variations.*.existing_images' => 'nullable|array',
|
||||
'variations.*.existing_images.*' => 'nullable|string',
|
||||
], [
|
||||
// Основные поля
|
||||
'name.required' => 'Название товара обязательно',
|
||||
'name.string' => 'Название товара должно быть строкой',
|
||||
'name.max' => 'Название товара не может превышать 255 символов',
|
||||
|
||||
'category_id.required' => 'Выберите категорию',
|
||||
'category_id.exists' => 'Выбранная категория не существует',
|
||||
|
||||
'brand_id.exists' => 'Выбранный бренд не существует',
|
||||
|
||||
'meta_title.max' => 'Meta Title не может превышать 255 символов',
|
||||
|
||||
// Вариации
|
||||
'variations.required' => 'Добавьте хотя бы одну вариацию',
|
||||
'variations.array' => 'Некорректный формат вариаций',
|
||||
'variations.min' => 'Добавьте хотя бы одну вариацию',
|
||||
|
||||
'variations.*.id.exists' => 'Вариация с ID :input не найдена',
|
||||
|
||||
'variations.*.name.required' => 'Название вариации обязательно',
|
||||
'variations.*.name.string' => 'Название вариации должно быть строкой',
|
||||
'variations.*.name.max' => 'Название вариации не может превышать 255 символов',
|
||||
|
||||
'variations.*.sku.required' => 'Артикул (SKU) обязателен',
|
||||
'variations.*.sku.string' => 'Артикул должен быть строкой',
|
||||
'variations.*.sku.max' => 'Артикул не может превышать 100 символов',
|
||||
|
||||
'variations.*.price.required' => 'Цена обязательна',
|
||||
'variations.*.price.numeric' => 'Цена должна быть числом',
|
||||
'variations.*.price.min' => 'Цена не может быть отрицательной',
|
||||
|
||||
'variations.*.old_price.numeric' => 'Старая цена должна быть числом',
|
||||
'variations.*.old_price.min' => 'Старая цена не может быть отрицательной',
|
||||
|
||||
'variations.*.stock.required' => 'Количество обязательно',
|
||||
'variations.*.stock.integer' => 'Количество должно быть целым числом',
|
||||
'variations.*.stock.min' => 'Количество не может быть отрицательным',
|
||||
|
||||
'variations.*.is_default.boolean' => 'Поле "Основная вариация" должно быть true или false',
|
||||
|
||||
'variations.*.attributes.array' => 'Некорректный формат атрибутов вариации',
|
||||
|
||||
'variations.*.attributes.flavor.string' => 'Вкус должен быть строкой',
|
||||
'variations.*.attributes.flavor.max' => 'Вкус не может превышать 100 символов',
|
||||
|
||||
'variations.*.attributes.color.string' => 'Цвет должен быть строкой',
|
||||
'variations.*.attributes.color.max' => 'Цвет не может превышать 100 символов',
|
||||
|
||||
'variations.*.attributes.size.string' => 'Размер должен быть строкой',
|
||||
'variations.*.attributes.size.max' => 'Размер не может превышать 50 символов',
|
||||
|
||||
'variations.*.attributes.weight.numeric' => 'Вес должен быть числом',
|
||||
'variations.*.attributes.weight.min' => 'Вес не может быть отрицательным',
|
||||
|
||||
// Изображения
|
||||
'variations.*.images.array' => 'Некорректный формат изображений',
|
||||
|
||||
'variations.*.images.*.image' => 'Файл должен быть изображением',
|
||||
'variations.*.images.*.mimes' => 'Допустимые форматы изображений: jpg, jpeg, png, webp',
|
||||
'variations.*.images.*.max' => 'Размер изображения не должен превышать 2 МБ',
|
||||
|
||||
'variations.*.removed_images.array' => 'Некорректный формат списка удаляемых изображений',
|
||||
'variations.*.removed_images.*.string' => 'Путь к удаляемому изображению должен быть строкой',
|
||||
|
||||
'variations.*.existing_images.array' => 'Некорректный формат списка существующих изображений',
|
||||
'variations.*.existing_images.*.string' => 'Путь к существующему изображению должен быть строкой',
|
||||
|
||||
// Атрибуты товара
|
||||
'attributes.array' => 'Некорректный формат характеристик',
|
||||
'attributes.*.key.string' => 'Название характеристики должно быть строкой',
|
||||
'attributes.*.value.string' => 'Значение характеристики должно быть строкой',
|
||||
]);
|
||||
|
||||
DB::beginTransaction();
|
||||
|
||||
try {
|
||||
// Обновляем slug если изменилось название
|
||||
$newSlug = Str::slug($validated['name']);
|
||||
$oldSlug = $product->slug;
|
||||
|
||||
if ($oldSlug != $newSlug) {
|
||||
$slug = $newSlug;
|
||||
$counter = 1;
|
||||
while (Product::where('slug', $slug)->where('id', '!=', $id)->exists()) {
|
||||
$slug = $newSlug . '-' . $counter;
|
||||
$counter++;
|
||||
}
|
||||
$product->slug = $slug;
|
||||
$this->renameProductFolder($oldSlug, $slug, $product);
|
||||
}
|
||||
|
||||
// Обновляем товар
|
||||
$product->update([
|
||||
'name' => $validated['name'],
|
||||
'description' => $validated['description'],
|
||||
'brand_id' => $validated['brand_id'],
|
||||
'category_id' => $validated['category_id'],
|
||||
'is_active' => $request->boolean('is_active'),
|
||||
'meta_title' => $validated['meta_title'],
|
||||
'meta_description' => $validated['meta_description'],
|
||||
'meta_keywords' => $validated['meta_keywords'],
|
||||
]);
|
||||
|
||||
// Обновляем атрибуты товара
|
||||
ProductAttribute::where('product_id', $product->id)->delete();
|
||||
if (!empty($validated['attributes'])) {
|
||||
foreach ($validated['attributes'] as $attr) {
|
||||
if (!empty($attr['key']) && !empty($attr['value'])) {
|
||||
ProductAttribute::create([
|
||||
'product_id' => $product->id,
|
||||
'key' => $attr['key'],
|
||||
'value' => $attr['value'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$existingVariationIds = [];
|
||||
|
||||
foreach ($validated['variations'] as $index => $variationData) {
|
||||
if (isset($variationData['id']) && $variationData['id']) {
|
||||
$variation = ProductVariation::find($variationData['id']);
|
||||
|
||||
if ($variation && $variation->product_id == $product->id) {
|
||||
$variation->update([
|
||||
'name' => $variationData['name'],
|
||||
'sku' => $variationData['sku'],
|
||||
'price' => $variationData['price'],
|
||||
'old_price' => $variationData['old_price'] ?? null,
|
||||
'stock' => $variationData['stock'],
|
||||
'is_default' => $variationData['is_default'] ?? false,
|
||||
]);
|
||||
|
||||
// Обновляем атрибуты вариации
|
||||
VariationAttribute::where('variation_id', $variation->id)->delete();
|
||||
if (!empty($variationData['attributes'])) {
|
||||
foreach ($variationData['attributes'] as $key => $value) {
|
||||
if (!empty($value) || $value === 0 || $value === '0') {
|
||||
VariationAttribute::create([
|
||||
'variation_id' => $variation->id,
|
||||
'key' => $key,
|
||||
'value' => $value,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========== ОБРАБОТКА ИЗОБРАЖЕНИЙ ==========
|
||||
// 1. Удаляем отмеченные изображения
|
||||
if (!empty($variationData['removed_images']) && is_array($variationData['removed_images'])) {
|
||||
foreach ($variationData['removed_images'] as $imagePath) {
|
||||
$image = VariationImage::where('variation_id', $variation->id)
|
||||
->where('path', $imagePath)
|
||||
->first();
|
||||
if ($image) {
|
||||
$fullPath = public_path($imagePath);
|
||||
if (file_exists($fullPath) && is_file($fullPath)) {
|
||||
@unlink($fullPath);
|
||||
}
|
||||
$image->delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Обновляем порядок существующих изображений
|
||||
if (!empty($variationData['existing_images']) && is_array($variationData['existing_images'])) {
|
||||
foreach ($variationData['existing_images'] as $sortOrder => $imagePath) {
|
||||
$image = VariationImage::where('variation_id', $variation->id)
|
||||
->where('path', $imagePath)
|
||||
->first();
|
||||
if ($image) {
|
||||
$image->sort_order = $sortOrder;
|
||||
$image->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Сохраняем новые изображения
|
||||
if ($request->hasFile("variations.{$index}.images")) {
|
||||
$files = $request->file("variations.{$index}.images");
|
||||
$validFiles = array_filter($files, function ($file) {
|
||||
return $file !== null && $file->isValid();
|
||||
});
|
||||
|
||||
if (!empty($validFiles)) {
|
||||
$this->saveVariationImages($validFiles, $product->slug, $variation->id);
|
||||
}
|
||||
}
|
||||
|
||||
$existingVariationIds[] = $variation->id;
|
||||
}
|
||||
} else {
|
||||
// Создаем новую вариацию
|
||||
$variation = ProductVariation::create([
|
||||
'product_id' => $product->id,
|
||||
'name' => $variationData['name'],
|
||||
'sku' => $variationData['sku'],
|
||||
'price' => $variationData['price'],
|
||||
'old_price' => $variationData['old_price'] ?? null,
|
||||
'stock' => $variationData['stock'],
|
||||
'is_default' => $variationData['is_default'] ?? false,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// Сохраняем атрибуты
|
||||
if (!empty($variationData['attributes'])) {
|
||||
foreach ($variationData['attributes'] as $key => $value) {
|
||||
if (!empty($value) || $value === 0 || $value === '0') {
|
||||
VariationAttribute::create([
|
||||
'variation_id' => $variation->id,
|
||||
'key' => $key,
|
||||
'value' => $value,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Сохраняем изображения
|
||||
if ($request->hasFile("variations.{$index}.images")) {
|
||||
$files = $request->file("variations.{$index}.images");
|
||||
$validFiles = array_filter($files, function ($file) {
|
||||
return $file !== null && $file->isValid();
|
||||
});
|
||||
|
||||
if (!empty($validFiles)) {
|
||||
$this->saveVariationImages($validFiles, $product->slug, $variation->id);
|
||||
}
|
||||
}
|
||||
|
||||
$existingVariationIds[] = $variation->id;
|
||||
}
|
||||
}
|
||||
|
||||
// Удаляем вариации, которых нет в форме
|
||||
$variationsToDelete = ProductVariation::where('product_id', $product->id)
|
||||
->whereNotIn('id', $existingVariationIds)
|
||||
->get();
|
||||
|
||||
foreach ($variationsToDelete as $variation) {
|
||||
// Удаляем изображения из БД и файловой системы
|
||||
$images = VariationImage::where('variation_id', $variation->id)->get();
|
||||
foreach ($images as $image) {
|
||||
$fullPath = public_path($image->path);
|
||||
if (file_exists($fullPath) && is_file($fullPath)) {
|
||||
@unlink($fullPath);
|
||||
}
|
||||
$image->delete();
|
||||
}
|
||||
|
||||
// Удаляем атрибуты
|
||||
VariationAttribute::where('variation_id', $variation->id)->delete();
|
||||
|
||||
// Удаляем папку
|
||||
$folderPath = public_path('assets/images/products/' . $product->slug . '/variation_' . $variation->id);
|
||||
if (file_exists($folderPath) && is_dir($folderPath)) {
|
||||
$this->deleteDirectory($folderPath);
|
||||
}
|
||||
|
||||
$variation->delete();
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
|
||||
return redirect()->route('admin.products')
|
||||
->with('success', 'Товар "' . $product->name . '" успешно обновлен');
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
Log::error('Product update error: ' . $e->getMessage(), ['trace' => $e->getTraceAsString()]);
|
||||
return redirect()->back()
|
||||
->withInput()
|
||||
->with('error', 'Ошибка при обновлении товара: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function saveVariationImages($images, $productSlug, $variationId)
|
||||
{
|
||||
$folder = public_path('assets/images/products/' . $productSlug . '/variation_' . $variationId);
|
||||
|
||||
if (!file_exists($folder)) {
|
||||
mkdir($folder, 0755, true);
|
||||
}
|
||||
|
||||
// Получаем текущий максимальный sort_order
|
||||
$maxSortOrder = VariationImage::where('variation_id', $variationId)->max('sort_order');
|
||||
$nextIndex = ($maxSortOrder !== null) ? $maxSortOrder + 1 : 0;
|
||||
|
||||
foreach ($images as $index => $image) {
|
||||
if ($image && $image->isValid()) {
|
||||
$extension = $image->getClientOriginalExtension();
|
||||
$filename = ($nextIndex + $index) . '.' . $extension;
|
||||
$destinationPath = $folder . '/' . $filename;
|
||||
|
||||
$image->move($folder, $filename);
|
||||
|
||||
if (file_exists($destinationPath)) {
|
||||
VariationImage::create([
|
||||
'variation_id' => $variationId,
|
||||
'path' => 'assets/images/products/' . $productSlug . '/variation_' . $variationId . '/' . $filename,
|
||||
'sort_order' => $nextIndex + $index,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function renameProductFolder($oldSlug, $newSlug, $product)
|
||||
{
|
||||
$oldFolder = public_path('assets/images/products/' . $oldSlug);
|
||||
$newFolder = public_path('assets/images/products/' . $newSlug);
|
||||
|
||||
if (file_exists($oldFolder) && is_dir($oldFolder)) {
|
||||
if (file_exists($newFolder)) {
|
||||
$this->mergeDirectories($oldFolder, $newFolder);
|
||||
$this->deleteDirectory($oldFolder);
|
||||
} else {
|
||||
rename($oldFolder, $newFolder);
|
||||
}
|
||||
|
||||
// Обновляем пути в БД
|
||||
$variations = ProductVariation::where('product_id', $product->id)->get();
|
||||
foreach ($variations as $variation) {
|
||||
$images = VariationImage::where('variation_id', $variation->id)->get();
|
||||
foreach ($images as $image) {
|
||||
$image->path = str_replace('assets/images/products/' . $oldSlug, 'assets/images/products/' . $newSlug, $image->path);
|
||||
$image->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function mergeDirectories($source, $destination)
|
||||
{
|
||||
if (!is_dir($destination)) {
|
||||
mkdir($destination, 0777, true);
|
||||
}
|
||||
|
||||
$files = scandir($source);
|
||||
foreach ($files as $file) {
|
||||
if ($file == '.' || $file == '..') continue;
|
||||
|
||||
$sourcePath = $source . '/' . $file;
|
||||
$destPath = $destination . '/' . $file;
|
||||
|
||||
if (is_dir($sourcePath)) {
|
||||
$this->mergeDirectories($sourcePath, $destPath);
|
||||
rmdir($sourcePath);
|
||||
} else {
|
||||
copy($sourcePath, $destPath);
|
||||
unlink($sourcePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function deleteDirectory($dir)
|
||||
{
|
||||
if (!file_exists($dir)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!is_dir($dir)) {
|
||||
return unlink($dir);
|
||||
}
|
||||
|
||||
foreach (scandir($dir) as $item) {
|
||||
if ($item == '.' || $item == '..') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!$this->deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return rmdir($dir);
|
||||
}
|
||||
|
||||
public function checkSku(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'sku' => 'required|string',
|
||||
'variation_id' => 'nullable|exists:product_variations,id',
|
||||
'product_id' => 'nullable|exists:products,id'
|
||||
]);
|
||||
|
||||
$sku = $request->sku;
|
||||
$variationId = $request->variation_id;
|
||||
$productId = $request->product_id;
|
||||
|
||||
$isUnique = ProductVariation::isSkuUnique($sku, $variationId, $productId);
|
||||
|
||||
return response()->json([
|
||||
'unique' => $isUnique,
|
||||
'message' => $isUnique ? null : 'Артикул "' . $sku . '" уже используется'
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$product = Product::findOrFail($id);
|
||||
$productName = $product->name;
|
||||
|
||||
foreach ($product->variations as $variation) {
|
||||
$images = VariationImage::where('variation_id', $variation->id)->get();
|
||||
foreach ($images as $image) {
|
||||
$fullPath = public_path($image->path);
|
||||
if (file_exists($fullPath) && is_file($fullPath)) {
|
||||
@unlink($fullPath);
|
||||
}
|
||||
}
|
||||
$folderPath = public_path('assets/images/products/' . $product->slug . '/variation_' . $variation->id);
|
||||
if (file_exists($folderPath) && is_dir($folderPath)) {
|
||||
$this->deleteDirectory($folderPath);
|
||||
}
|
||||
}
|
||||
|
||||
$productFolder = public_path('assets/images/products/' . $product->slug);
|
||||
if (file_exists($productFolder) && is_dir($productFolder)) {
|
||||
$this->deleteDirectory($productFolder);
|
||||
}
|
||||
|
||||
$product->delete();
|
||||
|
||||
return redirect()->route('admin.products')
|
||||
->with('success', 'Товар "' . $productName . '" успешно удален');
|
||||
}
|
||||
|
||||
public function duplicate($id)
|
||||
{
|
||||
DB::beginTransaction();
|
||||
|
||||
try {
|
||||
$original = Product::with(['variations.attributes', 'variations.images'])->findOrFail($id);
|
||||
|
||||
$newProduct = $original->replicate();
|
||||
$newProduct->name = $original->name . ' (копия)';
|
||||
$newProduct->slug = Str::slug($newProduct->name) . '-' . uniqid();
|
||||
$newProduct->created_at = now();
|
||||
$newProduct->updated_at = now();
|
||||
$newProduct->save();
|
||||
|
||||
// Копируем атрибуты товара
|
||||
foreach ($original->attributes as $attr) {
|
||||
ProductAttribute::create([
|
||||
'product_id' => $newProduct->id,
|
||||
'key' => $attr->key,
|
||||
'value' => $attr->value,
|
||||
]);
|
||||
}
|
||||
|
||||
// Копируем вариации
|
||||
foreach ($original->variations as $variation) {
|
||||
$newVariation = $variation->replicate();
|
||||
$newVariation->product_id = $newProduct->id;
|
||||
$newVariation->sku = $variation->sku . '-copy-' . uniqid();
|
||||
$newVariation->created_at = now();
|
||||
$newVariation->updated_at = now();
|
||||
$newVariation->save();
|
||||
|
||||
// Копируем атрибуты вариации
|
||||
foreach ($variation->attributes as $attr) {
|
||||
VariationAttribute::create([
|
||||
'variation_id' => $newVariation->id,
|
||||
'key' => $attr->key,
|
||||
'value' => $attr->value,
|
||||
]);
|
||||
}
|
||||
|
||||
// Копируем изображения
|
||||
$newFolder = public_path('assets/images/products/' . $newProduct->slug . '/variation_' . $newVariation->id);
|
||||
if (!file_exists($newFolder)) {
|
||||
mkdir($newFolder, 0755, true);
|
||||
}
|
||||
|
||||
foreach ($variation->images as $image) {
|
||||
$oldPath = public_path($image->path);
|
||||
$filename = basename($image->path);
|
||||
$newPath = $newFolder . '/' . $filename;
|
||||
|
||||
if (file_exists($oldPath)) {
|
||||
copy($oldPath, $newPath);
|
||||
VariationImage::create([
|
||||
'variation_id' => $newVariation->id,
|
||||
'path' => 'assets/images/products/' . $newProduct->slug . '/variation_' . $newVariation->id . '/' . $filename,
|
||||
'sort_order' => $image->sort_order,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
|
||||
return redirect()->route('admin.products')
|
||||
->with('success', 'Товар "' . $original->name . '" успешно скопирован. Новая версия: "' . $newProduct->name . '"');
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
Log::error('Product duplicate error: ' . $e->getMessage());
|
||||
return redirect()->back()
|
||||
->with('error', 'Ошибка при копировании товара: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
109
app/Http/Controllers/Admin/RolesController.php
Normal file
109
app/Http/Controllers/Admin/RolesController.php
Normal file
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class RolesController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$roles = Role::with('permissions')->paginate(15);
|
||||
|
||||
return view('admin.roles.roles', compact('roles'));
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
$permissions = Permission::all();
|
||||
|
||||
return view('admin.roles.create', compact('permissions'));
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'slug' => 'required|string|max:255|unique:roles',
|
||||
'description' => 'nullable|string',
|
||||
'permissions' => 'nullable|array',
|
||||
'permissions.*' => 'exists:permissions,id'
|
||||
], [
|
||||
'name.required' => 'Обязательно для заполнения',
|
||||
'name.max' => 'Не более 255 символов',
|
||||
'slug.required' => 'Обязательно для заполнения',
|
||||
'slug.max' => 'Не более 255 символов',
|
||||
'slug.unique' => 'Такой slug уже существует',
|
||||
'permissions.*.exists' => 'Право не найдено'
|
||||
]);
|
||||
|
||||
$role = Role::create([
|
||||
'name' => $request->name,
|
||||
'slug' => $request->slug,
|
||||
'description' => $request->description
|
||||
]);
|
||||
|
||||
if ($request->has('permissions')) {
|
||||
$role->permissions()->attach($request->permissions);
|
||||
}
|
||||
|
||||
return redirect()->route('admin.roles')
|
||||
->with('success', 'Роль "' . $role->name . '" успешно создана');
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
$role = Role::with('permissions')->findOrFail($id);
|
||||
$permissions = Permission::all();
|
||||
|
||||
return view('admin.roles.edit', compact('role', 'permissions'));
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$role = Role::findOrFail($id);
|
||||
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'slug' => 'required|string|max:255|unique:roles,slug,' . $id,
|
||||
'description' => 'nullable|string',
|
||||
'permissions' => 'nullable|array',
|
||||
'permissions.*' => 'exists:permissions,id'
|
||||
]);
|
||||
|
||||
$role->update([
|
||||
'name' => $request->name,
|
||||
'slug' => $request->slug,
|
||||
'description' => $request->description
|
||||
]);
|
||||
|
||||
$role->permissions()->sync($request->permissions ?? []);
|
||||
|
||||
return redirect()->route('admin.roles')
|
||||
->with('success', 'Роль "' . $role->name . '" успешно обновлена');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$role = Role::findOrFail($id);
|
||||
|
||||
$usersCount = User::where('role_id', $role->id)->count();
|
||||
|
||||
if ($usersCount > 0) {
|
||||
return redirect()->route('admin.roles')
|
||||
->with('error', 'Нельзя удалить роль, у которой есть пользователи');
|
||||
}
|
||||
|
||||
$roleName = $role->name;
|
||||
$role->permissions()->detach();
|
||||
$role->delete();
|
||||
|
||||
return redirect()->route('admin.roles')
|
||||
->with('success', 'Роль "' . $roleName . '" успешно удалена');
|
||||
}
|
||||
}
|
||||
133
app/Http/Controllers/Admin/UsersController.php
Normal file
133
app/Http/Controllers/Admin/UsersController.php
Normal file
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use App\Models\Role;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
||||
class UsersController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
$query = User::with('role');
|
||||
|
||||
if ($request->filled('search')) {
|
||||
$search = $request->search;
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('name', 'like', "%{$search}%")
|
||||
->orWhere('email', 'like', "%{$search}%");
|
||||
});
|
||||
}
|
||||
|
||||
$users = $query->orderBy('created_at', 'desc')->paginate(15);
|
||||
$users->appends($request->all());
|
||||
|
||||
return view('admin.users.users', compact('users'));
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
$roles = Role::all();
|
||||
return view('admin.users.create', compact('roles'));
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'email' => 'required|email|max:255|unique:users',
|
||||
'phone' => 'nullable|string|max:20',
|
||||
'password' => 'required|string|min:8|confirmed',
|
||||
'role_id' => 'required|exists:roles,id'
|
||||
], [
|
||||
'name.required' => 'Обязательно для заполнения',
|
||||
'name.max' => 'Не более 255 символов',
|
||||
'email.required' => 'Обязательно для заполнения',
|
||||
'email.email' => 'Введите корректный email',
|
||||
'email.max' => 'Не более 255 символов',
|
||||
'email.unique' => 'Этот email уже занят',
|
||||
'phone.max' => 'Не более 20 символов',
|
||||
'password.required' => 'Обязательно для заполнения',
|
||||
'password.min' => 'Минимум 8 символов',
|
||||
'password.confirmed' => 'Пароли не совпадают',
|
||||
'role_id.required' => 'Обязательно для заполнения'
|
||||
]);
|
||||
|
||||
$user = User::create([
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'phone' => $request->phone,
|
||||
'password' => Hash::make($request->password),
|
||||
'role_id' => $request->role_id
|
||||
]);
|
||||
|
||||
return redirect()->route('admin.users')
|
||||
->with('success', 'Пользователь "' . $user->name . '" успешно создан');
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
$user = User::findOrFail($id);
|
||||
$roles = Role::all();
|
||||
return view('admin.users.edit', compact('user', 'roles'));
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$user = User::findOrFail($id);
|
||||
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'email' => 'required|email|max:255|unique:users,email,' . $id,
|
||||
'phone' => 'nullable|string|max:20',
|
||||
'password' => 'nullable|string|min:8|confirmed',
|
||||
'role_id' => 'required|exists:roles,id'
|
||||
], [
|
||||
'name.required' => 'Обязательно для заполнения',
|
||||
'name.max' => 'Не более 255 символов',
|
||||
'email.required' => 'Обязательно для заполнения',
|
||||
'email.email' => 'Введите корректный email',
|
||||
'email.max' => 'Не более 255 символов',
|
||||
'email.unique' => 'Этот email уже занят',
|
||||
'phone.max' => 'Не более 20 символов',
|
||||
'password.min' => 'Минимум 8 символов',
|
||||
'password.confirmed' => 'Пароли не совпадают',
|
||||
'role_id.required' => 'Обязательно для заполнения'
|
||||
]);
|
||||
|
||||
$data = [
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'phone' => $request->phone,
|
||||
'role_id' => $request->role_id
|
||||
];
|
||||
|
||||
if ($request->filled('password')) {
|
||||
$data['password'] = Hash::make($request->password);
|
||||
}
|
||||
|
||||
$user->update($data);
|
||||
|
||||
return redirect()->route('admin.users')
|
||||
->with('success', 'Пользователь "' . $user->name . '" успешно обновлен');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$user = User::findOrFail($id);
|
||||
|
||||
if ($user->id === auth()->id()) {
|
||||
return redirect()->route('admin.users')
|
||||
->with('error', 'Нельзя удалить самого себя');
|
||||
}
|
||||
|
||||
$userName = $user->name;
|
||||
$user->delete();
|
||||
|
||||
return redirect()->route('admin.users')
|
||||
->with('success', 'Пользователь "' . $userName . '" успешно удален');
|
||||
}
|
||||
}
|
||||
50
app/Http/Controllers/Auth/LoginController.php
Normal file
50
app/Http/Controllers/Auth/LoginController.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
class LoginController extends Controller
|
||||
{
|
||||
public function showLoginForm()
|
||||
{
|
||||
return view('auth.login');
|
||||
}
|
||||
|
||||
public function login(Request $request)
|
||||
{
|
||||
$credentials = $request->validate([
|
||||
'email' => 'required|email',
|
||||
'password' => 'required|string',
|
||||
], [
|
||||
'email.required' => 'Введите email',
|
||||
'email.email' => 'Введите корректный email',
|
||||
'password.required' => 'Введите пароль',
|
||||
]);
|
||||
|
||||
$remember = $request->has('save_checkbox');
|
||||
|
||||
if (Auth::attempt($credentials, $remember)) {
|
||||
$request->session()->regenerate();
|
||||
|
||||
return redirect()->intended('/');
|
||||
}
|
||||
|
||||
return back()->withErrors([
|
||||
'email' => 'Неверный email или пароль',
|
||||
])->onlyInput('email');
|
||||
}
|
||||
|
||||
public function logout(Request $request)
|
||||
{
|
||||
Auth::logout();
|
||||
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return redirect('/');
|
||||
}
|
||||
}
|
||||
63
app/Http/Controllers/Auth/RegisterController.php
Normal file
63
app/Http/Controllers/Auth/RegisterController.php
Normal file
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\User;
|
||||
use App\Models\Role;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Auth\Events\Registered;
|
||||
|
||||
class RegisterController extends Controller
|
||||
{
|
||||
public function showRegisterForm()
|
||||
{
|
||||
return view('auth.register');
|
||||
}
|
||||
|
||||
public function register(Request $request)
|
||||
{
|
||||
$validator = Validator::make($request->all(), [
|
||||
'name' => 'required|string|max:255',
|
||||
'email' => 'required|string|email|max:255|unique:users',
|
||||
'phone' => 'required|string|max:20',
|
||||
'password' => 'required|string|min:8|confirmed',
|
||||
'save_checkbox' => 'accepted'
|
||||
], [
|
||||
'name.required' => 'Обязательно введите Ваше имя',
|
||||
'email.required' => 'Обязательно введите адрес электронной почты',
|
||||
'phone.required' => 'Обязательно введите Ваш номер телефона',
|
||||
'email.email' => 'Введите корректный адрес электронной почты',
|
||||
'email.unique' => 'Пользователь с таким адресом электронной почты уже существует',
|
||||
'password.required' => 'Поле пароль обязательно для заполнения',
|
||||
'password.min' => 'Пароль должен содержать минимум 8 символов',
|
||||
'password.confirmed' => 'Пароли не совпадают',
|
||||
'save_checkbox.accepted' => 'Необходимо согласие на обработку персональных данных'
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
return redirect()->back()
|
||||
->withErrors($validator)
|
||||
->withInput();
|
||||
}
|
||||
|
||||
$user = User::create([
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'phone' => $request->phone,
|
||||
'password' => Hash::make($request->password),
|
||||
]);
|
||||
|
||||
$defaultRole = Role::where('slug', 'registered_user')->first();
|
||||
if ($defaultRole) {
|
||||
$user->role()->attach($defaultRole->id);
|
||||
}
|
||||
|
||||
auth()->login($user);
|
||||
|
||||
return redirect()->intended('/')
|
||||
->with('success', 'Регистрация прошла успешно!');
|
||||
}
|
||||
}
|
||||
113
app/Http/Controllers/BrandController.php
Normal file
113
app/Http/Controllers/BrandController.php
Normal file
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Brand;
|
||||
use App\Models\Category;
|
||||
use App\Models\Product;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class BrandController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display all brands.
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$brands = Brand::active()
|
||||
->withCount('products')
|
||||
->orderBy('name')
|
||||
->paginate(20);
|
||||
|
||||
return view('brands.brands', compact('brands'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Display products by brand with filters.
|
||||
*/
|
||||
public function show(Request $request, $slug)
|
||||
{
|
||||
$brand = Brand::where('slug', $slug)
|
||||
->active()
|
||||
->firstOrFail();
|
||||
|
||||
// Получаем ID категорий, в которых есть товары этого бренда
|
||||
$categoryIds = $brand->products()
|
||||
->active()
|
||||
->pluck('category_id')
|
||||
->unique()
|
||||
->filter()
|
||||
->values()
|
||||
->toArray();
|
||||
|
||||
// Загружаем категории с родителями для построения полного пути
|
||||
$categories = Category::with(['parent', 'parent.parent'])
|
||||
->whereIn('id', $categoryIds)
|
||||
->active()
|
||||
->get();
|
||||
|
||||
// Формируем полный путь для каждой категории
|
||||
$categoriesWithPath = $categories->map(function ($category) {
|
||||
$path = [];
|
||||
$current = $category;
|
||||
|
||||
while ($current) {
|
||||
$path[] = $current->name;
|
||||
$current = $current->parent;
|
||||
}
|
||||
|
||||
$category->full_path = implode(' / ', array_reverse($path));
|
||||
return $category;
|
||||
})->sortBy('full_path');
|
||||
|
||||
// Диапазон цен
|
||||
$priceRange = DB::table('products')
|
||||
->join('product_variations', 'products.id', '=', 'product_variations.product_id')
|
||||
->where('products.brand_id', $brand->id)
|
||||
->where('products.is_active', true)
|
||||
->selectRaw('MIN(product_variations.price) as min_price, MAX(product_variations.price) as max_price')
|
||||
->first();
|
||||
|
||||
$minPrice = $priceRange->min_price ?? 0;
|
||||
$maxPrice = $priceRange->max_price ?? 10000;
|
||||
|
||||
// Запрос на продукты с фильтрацией
|
||||
$productsQuery = Product::with(['variations', 'category'])
|
||||
->where('brand_id', $brand->id)
|
||||
->active();
|
||||
|
||||
// Фильтрация по категориям
|
||||
if ($request->has('categories') && !empty($request->categories)) {
|
||||
$productsQuery->whereIn('category_id', $request->categories);
|
||||
}
|
||||
|
||||
// Фильтрация по цене
|
||||
if ($request->has('price-min') && $request->has('price-max')) {
|
||||
$min = (float) $request->get('price-min');
|
||||
$max = (float) $request->get('price-max');
|
||||
|
||||
$productsQuery->whereHas('variations', function ($q) use ($min, $max) {
|
||||
$q->whereBetween('price', [$min, $max]);
|
||||
});
|
||||
}
|
||||
|
||||
// Сортировка
|
||||
$sort = $request->get('sort', 'created_at');
|
||||
$order = $request->get('order', 'desc');
|
||||
|
||||
if ($sort === 'price') {
|
||||
$productsQuery->withMin('variations', 'price')
|
||||
->orderBy('variations_min_price', $order);
|
||||
} elseif ($sort === 'name') {
|
||||
$productsQuery->orderBy('name', $order);
|
||||
} else {
|
||||
$productsQuery->orderBy($sort, $order);
|
||||
}
|
||||
|
||||
$products = $productsQuery->paginate(20);
|
||||
$products->appends($request->all());
|
||||
|
||||
return view('brands.show', compact('brand', 'products', 'categoriesWithPath', 'minPrice', 'maxPrice'));
|
||||
}
|
||||
}
|
||||
179
app/Http/Controllers/CartController.php
Normal file
179
app/Http/Controllers/CartController.php
Normal file
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\CartItem;
|
||||
use App\Models\ProductVariation;
|
||||
use App\Models\Order;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class CartController extends Controller
|
||||
{
|
||||
/**
|
||||
* Отобразить корзину
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$cartItems = CartItem::getCartQuery()->get();
|
||||
$total = $cartItems->sum('total');
|
||||
|
||||
return view('cart.show', compact('cartItems', 'total'));
|
||||
}
|
||||
|
||||
public function add(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'variation_id' => 'required|exists:product_variations,id',
|
||||
'quantity' => 'required|integer|min:1'
|
||||
]);
|
||||
|
||||
$variation = ProductVariation::with('product')->find($request->variation_id);
|
||||
|
||||
if (!$variation) {
|
||||
if ($request->ajax()) {
|
||||
return response()->json(['success' => false, 'message' => 'Товар не найден'], 404);
|
||||
}
|
||||
return back()->with('error', 'Товар не найден');
|
||||
}
|
||||
|
||||
if ($variation->stock < $request->quantity) {
|
||||
if ($request->ajax()) {
|
||||
return response()->json(['success' => false, 'message' => 'Недостаточно товара на складе'], 422);
|
||||
}
|
||||
return back()->with('error', 'Недостаточно товара на складе');
|
||||
}
|
||||
|
||||
$cartItem = CartItem::findByVariation($request->variation_id);
|
||||
|
||||
if ($cartItem) {
|
||||
$newQuantity = $cartItem->quantity + $request->quantity;
|
||||
if ($variation->stock < $newQuantity) {
|
||||
if ($request->ajax()) {
|
||||
return response()->json(['success' => false, 'message' => 'Недостаточно товара на складе'], 422);
|
||||
}
|
||||
return back()->with('error', 'Недостаточно товара на складе');
|
||||
}
|
||||
$cartItem->update(['quantity' => $newQuantity]);
|
||||
} else {
|
||||
CartItem::create([
|
||||
'user_id' => Auth::id(),
|
||||
'session_id' => session()->getId(),
|
||||
'variation_id' => $request->variation_id,
|
||||
'quantity' => $request->quantity,
|
||||
'price' => $variation->price
|
||||
]);
|
||||
}
|
||||
|
||||
$cartCount = CartItem::getCount();
|
||||
|
||||
if ($request->ajax()) {
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Товар добавлен в корзину',
|
||||
'cart_count' => $cartCount
|
||||
]);
|
||||
}
|
||||
|
||||
return back()->with('success', 'Товар добавлен в корзину');
|
||||
}
|
||||
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$request->validate(['quantity' => 'required|integer|min:1']);
|
||||
|
||||
$cartItem = CartItem::find($id);
|
||||
|
||||
if (!$cartItem) {
|
||||
return response()->json(['error' => 'Товар не найден'], 404);
|
||||
}
|
||||
|
||||
$variation = $cartItem->variation;
|
||||
|
||||
if ($variation->stock < $request->quantity) {
|
||||
return response()->json(['error' => 'Недостаточно товара на складе'], 422);
|
||||
}
|
||||
|
||||
$cartItem->update(['quantity' => $request->quantity]);
|
||||
|
||||
$cartItems = CartItem::getCartQuery()->get();
|
||||
$cartTotal = $cartItems->sum('total');
|
||||
$totalItems = $cartItems->sum('quantity');
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'total' => $cartItem->total,
|
||||
'cart_total' => $cartTotal,
|
||||
'total_items' => $totalItems,
|
||||
'max_stock' => $variation->stock
|
||||
]);
|
||||
}
|
||||
|
||||
public function remove($id)
|
||||
{
|
||||
$cartItem = CartItem::findCartItem($id);
|
||||
|
||||
if ($cartItem) {
|
||||
$cartItem->delete();
|
||||
return redirect()->route('cart.index')->with('success', 'Товар удален из корзины');
|
||||
}
|
||||
|
||||
return redirect()->route('cart.index')->with('error', 'Товар не найден');
|
||||
}
|
||||
|
||||
public function clear()
|
||||
{
|
||||
CartItem::clear();
|
||||
return redirect()->route('cart.index')->with('success', 'Корзина очищена');
|
||||
}
|
||||
|
||||
public function checkout()
|
||||
{
|
||||
$cartItems = CartItem::getCartQuery()->get();
|
||||
|
||||
if ($cartItems->isEmpty()) {
|
||||
return redirect()->route('cart.index')->with('error', 'Корзина пуста');
|
||||
}
|
||||
|
||||
$total = $cartItems->sum('total');
|
||||
|
||||
return view('cart.checkout', compact('cartItems', 'total'));
|
||||
}
|
||||
|
||||
public function processOrder(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'customer_name' => 'required|string|max:255',
|
||||
'customer_email' => 'required|email|max:255',
|
||||
'customer_phone' => 'required|string|max:20',
|
||||
'shipping_address' => 'required_if:delivery_method,courier,express|max:1000',
|
||||
'delivery_method' => 'required|in:courier,pickup,express',
|
||||
'payment_method' => 'required|in:cash,card,online'
|
||||
], [
|
||||
'customer_name.required' => 'Поле обязательно для заполнения',
|
||||
'customer_email.required' => 'Поле обязательно для заполнения',
|
||||
'customer_email.email' => 'Введите корректный адрес электронной почты',
|
||||
'customer_phone.required' => 'Поле обязательно для заполнения',
|
||||
'shipping_address.required_if' => 'Адрес доставки обязателен для выбранного способа доставки',
|
||||
'delivery_method.required' => 'Выберите способ доставки',
|
||||
'payment_method.required' => 'Выберите способ оплаты'
|
||||
]);
|
||||
|
||||
|
||||
$cartItems = CartItem::getCartQuery()->get();
|
||||
|
||||
if ($cartItems->isEmpty()) {
|
||||
return back()->with('error', 'Корзина пуста');
|
||||
}
|
||||
|
||||
$order = Order::createFromCart($request->all(), $cartItems);
|
||||
|
||||
if ($order['success']) {
|
||||
return redirect()->route('orders.show', $order['order'])
|
||||
->with('success', 'Заказ оформлен! Номер заказа: ' . $order['order']->order_number);
|
||||
}
|
||||
|
||||
return back()->with('error', $order['message']);
|
||||
}
|
||||
}
|
||||
67
app/Http/Controllers/CategoryController.php
Normal file
67
app/Http/Controllers/CategoryController.php
Normal file
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Brand;
|
||||
use App\Models\Category;
|
||||
use App\Models\Product;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class CategoryController extends Controller
|
||||
{
|
||||
public function showByPath(Request $request, $path)
|
||||
{
|
||||
$category = Category::findByPath($path);
|
||||
|
||||
if (!$category) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$categoryIds = $category->getAllCategoryIds();
|
||||
|
||||
$brands = Brand::whereHas('products', function ($query) use ($categoryIds) {
|
||||
$query->whereIn('category_id', $categoryIds)
|
||||
->active();
|
||||
})
|
||||
->active()
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
$priceRange = DB::table('products')
|
||||
->join('product_variations', 'products.id', '=', 'product_variations.product_id')
|
||||
->whereIn('products.category_id', $categoryIds)
|
||||
->where('products.is_active', true)
|
||||
->where('product_variations.is_active', true)
|
||||
->selectRaw('MIN(product_variations.price) as min_price, MAX(product_variations.price) as max_price')
|
||||
->first();
|
||||
|
||||
$minPrice = $priceRange->min_price ?? 0;
|
||||
$maxPrice = $priceRange->max_price ?? 10000;
|
||||
|
||||
$productsQuery = $category->productsWithChildren()
|
||||
->with(['variations', 'brand'])
|
||||
->active();
|
||||
|
||||
if ($request->has('brands') && !empty($request->brands)) {
|
||||
$productsQuery->whereIn('brand_id', $request->brands);
|
||||
}
|
||||
|
||||
if ($request->has('price-min') && $request->has('price-max')) {
|
||||
$min = (float) $request->get('price-min');
|
||||
$max = (float) $request->get('price-max');
|
||||
|
||||
$productsQuery->whereHas('variations', function ($q) use ($min, $max) {
|
||||
$q->whereBetween('price', [$min, $max]);
|
||||
});
|
||||
}
|
||||
|
||||
$products = $productsQuery->orderBy('created_at', 'desc')->paginate(20);
|
||||
|
||||
$products->appends($request->all());
|
||||
|
||||
$children = $category->children()->active()->get();
|
||||
|
||||
return view('categories.show', compact('category', 'products', 'children', 'brands', 'minPrice', 'maxPrice'));
|
||||
}
|
||||
}
|
||||
12
app/Http/Controllers/Controller.php
Normal file
12
app/Http/Controllers/Controller.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||
use Illuminate\Foundation\Validation\ValidatesRequests;
|
||||
use Illuminate\Routing\Controller as BaseController;
|
||||
|
||||
class Controller extends BaseController
|
||||
{
|
||||
use AuthorizesRequests, ValidatesRequests;
|
||||
}
|
||||
53
app/Http/Controllers/HomeController.php
Normal file
53
app/Http/Controllers/HomeController.php
Normal file
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductVariation;
|
||||
use App\Models\ProductAttribute;
|
||||
use App\Models\VariationAttribute;
|
||||
use App\Models\VariationImage;
|
||||
use App\Models\Category;
|
||||
use App\Models\Contact;
|
||||
use App\Models\Brand;
|
||||
|
||||
class HomeController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$discountedProducts = ProductVariation::with(['product', 'images'])
|
||||
->discounted()
|
||||
->inStock()
|
||||
->active()
|
||||
->orderByRaw('(old_price - price) / old_price * 100 DESC')
|
||||
->limit(8)
|
||||
->get();
|
||||
|
||||
$categories = Category::active()->root()->orderBy('sort_order')->get();
|
||||
|
||||
$dryCatFood = Product::getForCarousel(21, 12);
|
||||
|
||||
$dryDogFood = Product::getForCarousel(3, 12);
|
||||
|
||||
return view('index', compact('discountedProducts', 'categories', 'dryCatFood', 'dryDogFood'));
|
||||
}
|
||||
|
||||
public function about()
|
||||
{
|
||||
|
||||
$topBrands = Brand::active()->popular()->limit(5)->get();
|
||||
|
||||
return view('about', compact('topBrands'));
|
||||
}
|
||||
|
||||
public function contacts()
|
||||
{
|
||||
return view('contacts');
|
||||
}
|
||||
|
||||
public function privacyPolicy()
|
||||
{
|
||||
return view('privacy-policy');
|
||||
}
|
||||
}
|
||||
90
app/Http/Controllers/MenuController.php
Normal file
90
app/Http/Controllers/MenuController.php
Normal file
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Category;
|
||||
use App\Models\Contact;
|
||||
use App\Models\Brand;
|
||||
use App\Models\Product;
|
||||
|
||||
class MenuController extends Controller
|
||||
{
|
||||
public function getMenuData()
|
||||
{
|
||||
$categories = Category::getTreeMenu();
|
||||
|
||||
$footerCategories = Category::root()
|
||||
->active()
|
||||
->orderBy('sort_order')
|
||||
->get();
|
||||
|
||||
$contacts = Contact::getData();
|
||||
|
||||
$popularBrands = Brand::active()->popular()->limit(8)->get();
|
||||
|
||||
return [
|
||||
'categories' => $categories,
|
||||
'contacts' => $contacts,
|
||||
'popularBrands' => $popularBrands,
|
||||
'footerCategories' => $footerCategories,
|
||||
];
|
||||
}
|
||||
|
||||
public function search(Request $request)
|
||||
{
|
||||
$query = trim($request->get('q', ''));
|
||||
|
||||
// Проверка на минимальную длину
|
||||
if (mb_strlen($query) < 3) {
|
||||
return redirect()->back()->with('error', 'Для поиска введите минимум 3 символа');
|
||||
}
|
||||
|
||||
// Поиск товаров
|
||||
$products = Product::with(['variations', 'brand', 'category'])
|
||||
->where('name', 'like', "%{$query}%")
|
||||
->orWhere('description', 'like', "%{$query}%")
|
||||
->orWhere('meta_keywords', 'like', "%{$query}%")
|
||||
->active()
|
||||
->paginate(20);
|
||||
|
||||
// Поиск брендов
|
||||
$brands = Brand::where('name', 'like', "%{$query}%")
|
||||
->orWhere('description', 'like', "%{$query}%")
|
||||
->active()
|
||||
->limit(10)
|
||||
->get();
|
||||
|
||||
return view('search.results', compact('products', 'brands', 'query'));
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX поиск для подсказок
|
||||
*/
|
||||
public function searchAjax(Request $request)
|
||||
{
|
||||
$query = trim($request->get('q', ''));
|
||||
|
||||
if (mb_strlen($query) < 2) {
|
||||
return response()->json([]);
|
||||
}
|
||||
|
||||
// Поиск товаров
|
||||
$products = Product::with('variations')
|
||||
->where('name', 'like', "%{$query}%")
|
||||
->active()
|
||||
->limit(5)
|
||||
->get(['id', 'name', 'slug']);
|
||||
|
||||
// Поиск брендов
|
||||
$brands = Brand::where('name', 'like', "%{$query}%")
|
||||
->active()
|
||||
->limit(3)
|
||||
->get(['id', 'name', 'slug']);
|
||||
|
||||
return response()->json([
|
||||
'products' => $products,
|
||||
'brands' => $brands
|
||||
]);
|
||||
}
|
||||
}
|
||||
35
app/Http/Controllers/OrderController.php
Normal file
35
app/Http/Controllers/OrderController.php
Normal file
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Order;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class OrderController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display user orders.
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$orders = Order::where('user_id', Auth::id())
|
||||
->orderBy('created_at', 'desc')
|
||||
->paginate(20);
|
||||
|
||||
return view('orders.orders', compact('orders'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Display order details.
|
||||
*/
|
||||
public function show(Order $order)
|
||||
{
|
||||
$user = Auth::user();
|
||||
if ($order->user_id !== Auth::id()) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
return view('profile.order-show', compact('order', 'user'));
|
||||
}
|
||||
}
|
||||
39
app/Http/Controllers/ProductsController.php
Normal file
39
app/Http/Controllers/ProductsController.php
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductVariation;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ProductsController extends Controller
|
||||
{
|
||||
public function show($slug)
|
||||
{
|
||||
$product = Product::with([
|
||||
'category',
|
||||
'category.parent',
|
||||
'brand',
|
||||
'variations',
|
||||
'variations.images',
|
||||
'attributes'
|
||||
])
|
||||
->where('slug', $slug)
|
||||
->where('is_active', true)
|
||||
->firstOrFail();
|
||||
|
||||
$defaultVariation = $product->default_variation;
|
||||
|
||||
return view('products.show', compact('product', 'defaultVariation'));
|
||||
}
|
||||
|
||||
public function getVariationImages($variationId)
|
||||
{
|
||||
$images = ProductVariation::getImagesDataById($variationId);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'images' => $images
|
||||
]);
|
||||
}
|
||||
}
|
||||
97
app/Http/Controllers/ProfileController.php
Normal file
97
app/Http/Controllers/ProfileController.php
Normal file
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\Order;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class ProfileController extends Controller
|
||||
{
|
||||
/**
|
||||
* Личный кабинет - главная
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$user = Auth::user();
|
||||
$activeOrders = Order::where('user_id', $user->id)
|
||||
->whereNotIn('delivery_status', ['delivered', 'cancelled'])
|
||||
->orderBy('created_at', 'desc')
|
||||
->get();
|
||||
|
||||
$archiveOrders = Order::where('user_id', $user->id)
|
||||
->whereIn('delivery_status', ['delivered', 'cancelled'])
|
||||
->orderBy('created_at', 'desc')
|
||||
->get();
|
||||
|
||||
return view('profile.profile', compact('user', 'activeOrders', 'archiveOrders'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Редактирование профиля
|
||||
*/
|
||||
public function edit()
|
||||
{
|
||||
$user = Auth::user();
|
||||
return view('profile.edit', compact('user'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновление профиля
|
||||
*/
|
||||
public function update(Request $request)
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'email' => [
|
||||
'required',
|
||||
'email',
|
||||
'max:255',
|
||||
Rule::unique('users')->ignore($user->id),
|
||||
],
|
||||
'phone' => 'nullable|string|max:20',
|
||||
'current_password' => 'nullable|required_with:password|current_password',
|
||||
'password' => 'nullable|string|min:8|confirmed',
|
||||
], [
|
||||
'name.required' => 'Обязательно для заполнения',
|
||||
'email.required' => 'Обязательно для заполнения',
|
||||
'email.email' => 'Введите корректный email',
|
||||
'email.unique' => 'Этот email уже занят',
|
||||
'current_password.required_with' => 'Введите текущий пароль',
|
||||
'current_password.current_password' => 'Неверный текущий пароль',
|
||||
'password.min' => 'Пароль должен содержать минимум 8 символов',
|
||||
'password.confirmed' => 'Пароли не совпадают',
|
||||
]);
|
||||
|
||||
$user->name = $request->name;
|
||||
$user->email = $request->email;
|
||||
$user->phone = $request->phone;
|
||||
|
||||
if ($request->filled('password')) {
|
||||
$user->password = Hash::make($request->password);
|
||||
}
|
||||
|
||||
$user->save();
|
||||
|
||||
return redirect()->route('profile.index')
|
||||
->with('success', 'Профиль успешно обновлен');
|
||||
}
|
||||
|
||||
/**
|
||||
* Детали заказа
|
||||
*/
|
||||
public function orderShow($id)
|
||||
{
|
||||
$order = Order::where('user_id', Auth::id())
|
||||
->with('items.variation.product')
|
||||
->findOrFail($id);
|
||||
$user = Auth::user();
|
||||
|
||||
return view('profile.order-show', compact('order', 'user'));
|
||||
}
|
||||
}
|
||||
69
app/Http/Kernel.php
Normal file
69
app/Http/Kernel.php
Normal file
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http;
|
||||
|
||||
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
||||
|
||||
class Kernel extends HttpKernel
|
||||
{
|
||||
/**
|
||||
* The application's global HTTP middleware stack.
|
||||
*
|
||||
* These middleware are run during every request to your application.
|
||||
*
|
||||
* @var array<int, class-string|string>
|
||||
*/
|
||||
protected $middleware = [
|
||||
// \App\Http\Middleware\TrustHosts::class,
|
||||
\App\Http\Middleware\TrustProxies::class,
|
||||
\Illuminate\Http\Middleware\HandleCors::class,
|
||||
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
|
||||
\App\Http\Middleware\TrimStrings::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* The application's route middleware groups.
|
||||
*
|
||||
* @var array<string, array<int, class-string|string>>
|
||||
*/
|
||||
protected $middlewareGroups = [
|
||||
'web' => [
|
||||
\App\Http\Middleware\EncryptCookies::class,
|
||||
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
|
||||
\Illuminate\Session\Middleware\StartSession::class,
|
||||
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
|
||||
\App\Http\Middleware\VerifyCsrfToken::class,
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
|
||||
'api' => [
|
||||
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
|
||||
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* The application's middleware aliases.
|
||||
*
|
||||
* Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
|
||||
*
|
||||
* @var array<string, class-string|string>
|
||||
*/
|
||||
protected $middlewareAliases = [
|
||||
'auth' => \App\Http\Middleware\Authenticate::class,
|
||||
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
|
||||
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
|
||||
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
|
||||
'can' => \Illuminate\Auth\Middleware\Authorize::class,
|
||||
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
|
||||
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
|
||||
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
|
||||
'signed' => \App\Http\Middleware\ValidateSignature::class,
|
||||
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
|
||||
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
|
||||
'permission' => \App\Http\Middleware\CheckPermission::class,
|
||||
];
|
||||
}
|
||||
17
app/Http/Middleware/Authenticate.php
Normal file
17
app/Http/Middleware/Authenticate.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Auth\Middleware\Authenticate as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class Authenticate extends Middleware
|
||||
{
|
||||
/**
|
||||
* Get the path the user should be redirected to when they are not authenticated.
|
||||
*/
|
||||
protected function redirectTo(Request $request): ?string
|
||||
{
|
||||
return $request->expectsJson() ? null : route('login');
|
||||
}
|
||||
}
|
||||
32
app/Http/Middleware/CheckPermission.php
Normal file
32
app/Http/Middleware/CheckPermission.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class CheckPermission
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, string $permission): Response
|
||||
{
|
||||
if (!Auth::check()) {
|
||||
abort(403, 'Для доступа необходимо авторизоваться');
|
||||
}
|
||||
|
||||
/** @var \App\Models\User $user */
|
||||
$user = Auth::user();
|
||||
|
||||
if (!$user->hasPermission($permission)) {
|
||||
abort(403, 'У вас нет прав для доступа к этой странице');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
20
app/Http/Middleware/CheckRole.php
Normal file
20
app/Http/Middleware/CheckRole.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class CheckRole
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
17
app/Http/Middleware/EncryptCookies.php
Normal file
17
app/Http/Middleware/EncryptCookies.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
|
||||
|
||||
class EncryptCookies extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the cookies that should not be encrypted.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
17
app/Http/Middleware/PreventRequestsDuringMaintenance.php
Normal file
17
app/Http/Middleware/PreventRequestsDuringMaintenance.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
|
||||
|
||||
class PreventRequestsDuringMaintenance extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be reachable while maintenance mode is enabled.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
30
app/Http/Middleware/RedirectIfAuthenticated.php
Normal file
30
app/Http/Middleware/RedirectIfAuthenticated.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class RedirectIfAuthenticated
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, string ...$guards): Response
|
||||
{
|
||||
$guards = empty($guards) ? [null] : $guards;
|
||||
|
||||
foreach ($guards as $guard) {
|
||||
if (Auth::guard($guard)->check()) {
|
||||
return redirect(RouteServiceProvider::HOME);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
19
app/Http/Middleware/TrimStrings.php
Normal file
19
app/Http/Middleware/TrimStrings.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
|
||||
|
||||
class TrimStrings extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the attributes that should not be trimmed.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
'current_password',
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
}
|
||||
20
app/Http/Middleware/TrustHosts.php
Normal file
20
app/Http/Middleware/TrustHosts.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Middleware\TrustHosts as Middleware;
|
||||
|
||||
class TrustHosts extends Middleware
|
||||
{
|
||||
/**
|
||||
* Get the host patterns that should be trusted.
|
||||
*
|
||||
* @return array<int, string|null>
|
||||
*/
|
||||
public function hosts(): array
|
||||
{
|
||||
return [
|
||||
$this->allSubdomainsOfApplicationUrl(),
|
||||
];
|
||||
}
|
||||
}
|
||||
28
app/Http/Middleware/TrustProxies.php
Normal file
28
app/Http/Middleware/TrustProxies.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Middleware\TrustProxies as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class TrustProxies extends Middleware
|
||||
{
|
||||
/**
|
||||
* The trusted proxies for this application.
|
||||
*
|
||||
* @var array<int, string>|string|null
|
||||
*/
|
||||
protected $proxies;
|
||||
|
||||
/**
|
||||
* The headers that should be used to detect proxies.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $headers =
|
||||
Request::HEADER_X_FORWARDED_FOR |
|
||||
Request::HEADER_X_FORWARDED_HOST |
|
||||
Request::HEADER_X_FORWARDED_PORT |
|
||||
Request::HEADER_X_FORWARDED_PROTO |
|
||||
Request::HEADER_X_FORWARDED_AWS_ELB;
|
||||
}
|
||||
22
app/Http/Middleware/ValidateSignature.php
Normal file
22
app/Http/Middleware/ValidateSignature.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
|
||||
|
||||
class ValidateSignature extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the query string parameters that should be ignored.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
// 'fbclid',
|
||||
// 'utm_campaign',
|
||||
// 'utm_content',
|
||||
// 'utm_medium',
|
||||
// 'utm_source',
|
||||
// 'utm_term',
|
||||
];
|
||||
}
|
||||
17
app/Http/Middleware/VerifyCsrfToken.php
Normal file
17
app/Http/Middleware/VerifyCsrfToken.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
|
||||
|
||||
class VerifyCsrfToken extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be excluded from CSRF verification.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
Reference in New Issue
Block a user