This commit is contained in:
2026-04-06 18:44:02 +05:00
commit d775fbb9ba
431 changed files with 31234 additions and 0 deletions

18
.dockerignore Normal file
View File

@@ -0,0 +1,18 @@
.git
.gitignore
node_modules
vendor
.env
.env.*
!.env.example
storage/logs/*
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
public/build
*.md
tests/
phpunit.xml
docker-compose*.yml
.editorconfig
.styleci.yml

18
.editorconfig Normal file
View File

@@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

59
.env.example Normal file
View File

@@ -0,0 +1,59 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1
VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

11
.gitattributes vendored Normal file
View File

@@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

19
.gitignore vendored Normal file
View File

@@ -0,0 +1,19 @@
/.phpunit.cache
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.env.production
.phpunit.result.cache
Homestead.json
Homestead.yaml
auth.json
npm-debug.log
yarn-error.log
/.fleet
/.idea
/.vscode

76
Dockerfile Normal file
View File

@@ -0,0 +1,76 @@
# ─────────────────────────────────────────────
# Stage 1: Build frontend assets
# ─────────────────────────────────────────────
FROM node:20-alpine AS node-builder
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci
COPY vite.config.js tailwind.config.js postcss.config.js ./
COPY resources/ resources/
COPY public/ public/
RUN npm run build
# ─────────────────────────────────────────────
# Stage 2: PHP application
# ─────────────────────────────────────────────
FROM php:8.2-fpm-alpine AS app
# System dependencies
RUN apk add --no-cache \
nginx \
supervisor \
curl \
libpng-dev \
libjpeg-turbo-dev \
libwebp-dev \
freetype-dev \
libzip-dev \
oniguruma-dev \
icu-dev \
&& docker-php-ext-configure gd --with-freetype --with-jpeg --with-webp \
&& docker-php-ext-install \
pdo_mysql \
mbstring \
gd \
zip \
bcmath \
intl \
opcache
# Install Composer
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
WORKDIR /var/www/html
# Copy composer files first for layer caching
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --optimize-autoloader --no-interaction
# Copy application source
COPY . .
# Copy built frontend assets from stage 1
COPY --from=node-builder /app/public/build public/build
# Laravel setup
RUN cp .env.example .env \
&& php artisan key:generate --force \
&& php artisan config:clear \
&& php artisan storage:link || true
# Permissions
RUN chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache \
&& chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache
# Copy config files
COPY docker/nginx/default.conf /etc/nginx/http.d/default.conf
COPY docker/php/php.ini $PHP_INI_DIR/conf.d/app.ini
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
EXPOSE 80
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]

66
README.md Normal file
View File

@@ -0,0 +1,66 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
You may also try the [Laravel Bootcamp](https://bootcamp.laravel.com), where you will be guided through building a modern Laravel application from scratch.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com/)**
- **[Tighten Co.](https://tighten.co)**
- **[WebReinvent](https://webreinvent.com/)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel/)**
- **[Cyber-Duck](https://cyber-duck.co.uk)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Jump24](https://jump24.co.uk)**
- **[Redberry](https://redberry.international/laravel/)**
- **[Active Logic](https://activelogic.com)**
- **[byte5](https://byte5.de)**
- **[OP.GG](https://op.gg)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

1462
TailAndPaws.sql Normal file

File diff suppressed because it is too large Load Diff

27
app/Console/Kernel.php Normal file
View File

@@ -0,0 +1,27 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule): void
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* The list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->reportable(function (Throwable $e) {
//
});
}
}

View 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 . '" успешно удален');
}
}

View 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 . '" успешно удалена');
}
}

View 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', 'Данные сайта успешно обновлены');
}
}

View 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);
}
}

View 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', 'Статус заказа обновлен');
}
}

View 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);
}
}

View 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());
}
}
}

View 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 . '" успешно удалена');
}
}

View 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 . '" успешно удален');
}
}

View 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('/');
}
}

View 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', 'Регистрация прошла успешно!');
}
}

View 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'));
}
}

View 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']);
}
}

View 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'));
}
}

View 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;
}

View 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');
}
}

View 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
]);
}
}

View 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'));
}
}

View 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
]);
}
}

View 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
View 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,
];
}

View 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');
}
}

View 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);
}
}

View 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);
}
}

View 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 = [
//
];
}

View 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 = [
//
];
}

View 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);
}
}

View 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',
];
}

View 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(),
];
}
}

View 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;
}

View 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',
];
}

View 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 = [
//
];
}

62
app/Models/Brand.php Normal file
View File

@@ -0,0 +1,62 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Brand extends Model
{
public $timestamps = false;
protected $fillable = [
'name',
'slug',
'description',
'logo',
'website',
'country',
'is_active',
];
protected $casts = [
'is_active' => 'boolean',
];
public function products(): HasMany
{
return $this->hasMany(Product::class);
}
public function activeProducts(): HasMany
{
return $this->hasMany(Product::class)->where('is_active', true);
}
public function getProductsCountAttribute(): int
{
return $this->activeProducts()->count();
}
public function scopeActive($query)
{
return $query->where('is_active', true);
}
public function scopePopular($query)
{
return $query->withCount('products')->orderBy('products_count', 'desc');
}
public function getLogoUrlAttribute(): string
{
if ($this->logo) {
$logoPath = 'assets/images/brands/' . $this->logo;
if (file_exists(public_path($logoPath))) {
return asset($logoPath);
}
}
return asset('assets/images/brands/default.svg');
}
}

97
app/Models/CartItem.php Normal file
View File

@@ -0,0 +1,97 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Auth;
class CartItem extends Model
{
protected $fillable = [
'user_id',
'session_id',
'variation_id',
'quantity',
'price'
];
protected $casts = [
'quantity' => 'integer',
'price' => 'decimal:2'
];
public function variation(): BelongsTo
{
return $this->belongsTo(ProductVariation::class);
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function getTotalAttribute(): float
{
return $this->quantity * $this->price;
}
/**
* Получить корзину для текущего пользователя/сессии
*/
public static function getCartQuery()
{
return self::with('variation.product')
->where(function ($query) {
if (Auth::check()) {
$query->where('user_id', Auth::id());
} else {
$query->where('session_id', session()->getId());
}
});
}
/**
* Получить количество товаров в корзине
*/
public static function getCount()
{
return self::getCartQuery()->sum('quantity');
}
/**
* Получить общую сумму корзины
*/
public static function getTotal()
{
return self::getCartQuery()->get()->sum('total');
}
/**
* Получить товар в корзине по вариации
*/
public static function findByVariation($variationId)
{
return self::getCartQuery()
->where('variation_id', $variationId)
->first();
}
/**
* Получить товар в корзине по ID
*/
public static function findCartItem($id)
{
return self::getCartQuery()
->where('id', $id)
->first();
}
/**
* Очистить корзину
*/
public static function clear()
{
return self::getCartQuery()->delete();
}
}

243
app/Models/Category.php Normal file
View File

@@ -0,0 +1,243 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Category extends Model
{
public $timestamps = false;
protected $fillable = [
'name',
'slug',
'description',
'icon',
'image',
'parent_id',
'sort_order',
'is_active'
];
protected $casts = [
'is_active' => 'boolean',
];
public function parent(): BelongsTo
{
return $this->belongsTo(Category::class, 'parent_id');
}
public function children(): HasMany
{
return $this->hasMany(Category::class, 'parent_id')->orderBy('sort_order');
}
public function descendants()
{
return $this->children()->with('descendants');
}
public function products(): HasMany
{
return $this->hasMany(Product::class, 'category_id');
}
public function getFullSlugAttribute(): string
{
$slugs = [];
$current = $this;
while ($current) {
$slugs[] = $current->slug;
$current = $current->parent;
}
return implode('/', array_reverse($slugs));
}
public function getUrlAttribute(): string
{
return route('category.show', $this->full_slug);
}
public function getBreadcrumbsAttribute()
{
$breadcrumbs = [];
$current = $this;
while ($current) {
array_unshift($breadcrumbs, [
'name' => $current->name,
'slug' => $current->slug,
'url' => $current->url
]);
$current = $current->parent;
}
return $breadcrumbs;
}
public function getPathAttribute()
{
$path = [];
$current = $this;
while ($current) {
array_unshift($path, $current->slug);
$current = $current->parent;
}
return implode('/', $path);
}
public function scopeActive($query)
{
return $query->where('is_active', true);
}
public function scopeRoot($query)
{
return $query->whereNull('parent_id');
}
public static function getTreeMenu()
{
return self::with('descendants')->root()->active()->orderBy('sort_order')->get();
}
public static function findByPath($path)
{
$slugs = explode('/', trim($path, '/'));
$category = null;
foreach ($slugs as $slug) {
if (!$category) {
$category = self::where('slug', $slug)
->whereNull('parent_id')
->active()
->first();
} else {
$category = $category->children()
->where('slug', $slug)
->active()
->first();
}
if (!$category) {
return null;
}
}
return $category;
}
public static function getSelectTree($maxLevel = 1)
{
$categories = self::with('parent')->get();
return $categories->map(function ($cat) {
$cat->level = $cat->calculateLevel();
return $cat;
})->filter(function ($cat) use ($maxLevel) {
return $cat->level < $maxLevel;
});
}
public static function getFlatTree()
{
$categories = self::with('parent')
->orderBy('parent_id')
->orderBy('sort_order')
->get();
return self::buildFlatTree($categories);
}
private static function buildFlatTree($categories, $parentId = null, $level = 0)
{
$result = collect();
foreach ($categories as $category) {
if ($category->parent_id == $parentId) {
$category->level = $level;
$result->push($category);
$children = self::buildFlatTree($categories, $category->id, $level + 1);
$result = $result->concat($children);
}
}
return $result;
}
public function getLevelAttribute()
{
return $this->calculateLevel();
}
public function calculateLevel($level = 0)
{
if ($this->parent) {
return $this->parent->calculateLevel($level + 1);
}
return $level;
}
public function isDescendantOf($ancestorId): bool
{
$current = $this;
while ($current) {
if ($current->id == $ancestorId) {
return true;
}
$current = $current->parent;
}
return false;
}
public function getIconUrlAttribute(): string
{
if ($this->icon !== NULL) {
$iconPath = 'assets/images/categories/icons/' . $this->icon;
if (file_exists(public_path($iconPath))) {
return asset($iconPath);
}
}
return asset('assets/images/categories/icons/default.svg');
}
public function getImageUrlAttribute(): string
{
if ($this->image !== NULL) {
$imagePath = 'assets/images/categories/images/' . $this->image;
if (file_exists(public_path($imagePath))) {
return asset($imagePath);
}
}
return asset('assets/images/categories/images/default.svg');
}
public function getAllCategoryIds(): array
{
$ids = [$this->id];
foreach ($this->children as $child) {
$ids = array_merge($ids, $child->getAllCategoryIds());
}
return $ids;
}
// В модели Category
public function productsWithChildren()
{
$categoryIds = $this->getAllCategoryIds();
return Product::whereIn('category_id', $categoryIds);
}
}

31
app/Models/Contact.php Normal file
View File

@@ -0,0 +1,31 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $fillable = [
'name',
'description',
'logo',
'favicon',
'phone',
'email',
'address',
'work_hours',
'telegram',
'whatsapp',
'vkontakte',
'meta_title',
'meta_description',
'meta_keywords',
];
public static function getData()
{
return self::first() ?? self::create();
}
}

203
app/Models/Order.php Normal file
View File

@@ -0,0 +1,203 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\DB;
class Order extends Model
{
protected $fillable = [
'order_number',
'user_id',
'customer_name',
'customer_email',
'customer_phone',
'shipping_address',
'subtotal',
'shipping_cost',
'discount',
'total',
'payment_method',
'payment_status',
'delivery_method',
'delivery_status',
'comment'
];
protected $casts = [
'subtotal' => 'decimal:2',
'shipping_cost' => 'decimal:2',
'discount' => 'decimal:2',
'total' => 'decimal:2'
];
const DELIVERY_STATUSES = [
'pending' => 'Ожидает обработки',
'processing' => 'В обработке',
'shipped' => 'Отправлен',
'delivered' => 'Доставлен',
'cancelled' => 'Отменён'
];
const PAYMENT_STATUSES = [
'pending' => 'Ожидает оплаты',
'paid' => 'Оплачен',
'failed' => 'Ошибка оплаты'
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function items(): HasMany
{
return $this->hasMany(OrderItem::class);
}
public static function generateOrderNumber(): string
{
return 'ORD-' . date('Ymd') . '-' . strtoupper(uniqid());
}
/**
* Создать заказ из корзины
*/
public static function createFromCart($data, $cartItems)
{
DB::beginTransaction();
try {
$subtotal = $cartItems->sum('total');
$shippingCost = self::calculateShipping($data['delivery_method']);
$total = $subtotal + $shippingCost;
$shippingAddress = null;
if (in_array($data['delivery_method'], ['courier', 'express'])) {
$shippingAddress = $data['shipping_address'];
}
$order = self::create([
'order_number' => self::generateOrderNumber(),
'user_id' => auth()->id(),
'customer_name' => $data['customer_name'],
'customer_email' => $data['customer_email'],
'customer_phone' => $data['customer_phone'],
'shipping_address' => $shippingAddress,
'subtotal' => $subtotal,
'shipping_cost' => $shippingCost,
'total' => $total,
'payment_method' => $data['payment_method'],
'delivery_method' => $data['delivery_method'],
'comment' => $data['comment'] ?? null
]);
foreach ($cartItems as $item) {
OrderItem::create([
'order_id' => $order->id,
'variation_id' => $item->variation_id,
'product_name' => $item->variation->product->name,
'variation_name' => $item->variation->name,
'sku' => $item->variation->sku,
'quantity' => $item->quantity,
'price' => $item->price,
'total' => $item->total
]);
$item->variation->decrement('stock', $item->quantity);
}
CartItem::clear();
DB::commit();
return ['success' => true, 'order' => $order];
} catch (\Exception $e) {
DB::rollBack();
return ['success' => false, 'message' => $e->getMessage()];
}
}
/**
* Рассчитать стоимость доставки
*/
private static function calculateShipping($method)
{
return match ($method) {
'express' => 300,
'courier' => 0,
'pickup' => 0,
default => 0,
};
}
public function getDeliveryStatusNameAttribute(): string
{
return self::DELIVERY_STATUSES[$this->delivery_status] ?? $this->delivery_status;
}
public function getPaymentStatusNameAttribute(): string
{
return self::PAYMENT_STATUSES[$this->payment_status] ?? $this->payment_status;
}
public function getDeliveryStatusColorAttribute(): string
{
return match ($this->delivery_status) {
'pending' => 'warning',
'processing' => 'info',
'shipped' => 'primary',
'delivered' => 'success',
'cancelled' => 'danger',
default => 'secondary'
};
}
public function getDeliveryStatusIconAttribute(): string
{
return match ($this->delivery_status) {
'pending' => 'bi-clock',
'processing' => 'bi-arrow-repeat',
'shipped' => 'bi-truck',
'delivered' => 'bi-check-circle',
'cancelled' => 'bi-x-circle',
default => 'bi-question-circle'
};
}
/**
* Получить все возможные статусы доставки для выпадающего списка
*/
public static function getDeliveryStatuses(): array
{
return self::DELIVERY_STATUSES;
}
/**
* Получить все возможные статусы оплаты для выпадающего списка
*/
public static function getPaymentStatuses(): array
{
return self::PAYMENT_STATUSES;
}
public static function getRevenue($startDate, $endDate, $paidOnly = true)
{
$query = self::query();
if ($paidOnly) {
$query->where('payment_status', 'paid');
}
return $query->whereBetween('created_at', [$startDate, $endDate])
->sum('total');
}
public static function getMonthlyRevenue()
{
return self::getRevenue(now()->startOfMonth(), now()->endOfMonth());
}
}

65
app/Models/OrderItem.php Normal file
View File

@@ -0,0 +1,65 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\DB;
class OrderItem extends Model
{
protected $fillable = [
'order_id',
'variation_id',
'product_name',
'variation_name',
'sku',
'quantity',
'price',
'total'
];
protected $casts = [
'quantity' => 'integer',
'price' => 'decimal:2',
'total' => 'decimal:2'
];
public function order(): BelongsTo
{
return $this->belongsTo(Order::class);
}
public function variation(): BelongsTo
{
return $this->belongsTo(ProductVariation::class);
}
public static function createFromCartItem($orderId, $cartItem)
{
return self::create([
'order_id' => $orderId,
'variation_id' => $cartItem->variation_id,
'product_name' => $cartItem->variation->product->name,
'variation_name' => $cartItem->variation->name,
'sku' => $cartItem->variation->sku,
'quantity' => $cartItem->quantity,
'price' => $cartItem->price,
'total' => $cartItem->total
]);
}
public function scopePopular($query, $limit = 5)
{
return $query->select(
'product_name',
'variation_name',
'variation_id',
DB::raw('SUM(quantity) as total_quantity'),
DB::raw('SUM(total) as total_revenue')
)
->groupBy('product_name', 'variation_name', 'variation_id')
->orderBy('total_quantity', 'desc')
->limit($limit);
}
}

28
app/Models/Permission.php Normal file
View File

@@ -0,0 +1,28 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Permission extends Model
{
public $timestamps = false;
protected $fillable = [
'name',
'slug',
'group',
'description',
];
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class)->withTimestamps();
}
public function scopeInGroup($query, string $group)
{
$query->where('group', $group);
}
}

183
app/Models/Product.php Normal file
View File

@@ -0,0 +1,183 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Product extends Model
{
protected $fillable = [
'name',
'slug',
'description',
'brand_id',
'category_id',
'is_active',
'meta_title',
'meta_description',
'meta_keywords',
];
protected $casts = [
'is_active' => 'boolean',
];
public function brand(): BelongsTo
{
return $this->belongsTo(Brand::class);
}
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
public function variations(): HasMany
{
return $this->hasMany(ProductVariation::class);
}
public function attributes(): HasMany
{
return $this->hasMany(ProductAttribute::class);
}
public function getDefaultVariationAttribute()
{
$defaultInStock = $this->variations->firstWhere(function ($variation) {
return $variation->is_default && $variation->stock > 0;
});
if ($defaultInStock) {
return $defaultInStock;
}
$anyInStock = $this->variations->firstWhere('stock', '>', 0);
if ($anyInStock) {
return $anyInStock;
}
return $this->variations->firstWhere('is_default', true) ?? $this->variations->first();
}
/**
* Получить URL главного изображения товара (из дефолтной вариации)
*/
public function getMainImageAttribute(): string
{
$defaultVariation = $this->default_variation;
if ($defaultVariation) {
return $defaultVariation->main_image_url;
}
return asset('assets/images/products/default.svg');
}
/**
* Получить изображения дефолтной вариации
*/
public function getDefaultVariationImages()
{
$defaultVariation = $this->default_variation;
if ($defaultVariation) {
return $defaultVariation->images;
}
return collect();
}
public static function getForCarousel($categoryId = null, $limit = 9, $itemsPerSlide = 3)
{
$query = self::with(['category', 'brand', 'variations'])
->active();
if ($categoryId) {
$query->byCategory($categoryId);
}
$products = $query->limit($limit)->get();
$products = $products->filter(function ($product) {
return $product->variations->isNotEmpty();
});
$products = $products->sortByDesc(function ($product) {
$defaultVariation = $product->default_variation;
if ($defaultVariation && $defaultVariation->stock > 0) {
return 3;
} elseif ($defaultVariation) {
return 2;
} elseif ($product->variations->firstWhere('stock', '>', 0)) {
return 1;
}
return 0;
});
return $products->chunk($itemsPerSlide);
}
public function getRatingAttribute(): array
{
return [
'score' => 4.9,
'count' => 1000
];
}
public function getMinPriceAttribute(): float
{
return $this->variations->min('price') ?? 0;
}
public function getMaxPriceAttribute(): float
{
return $this->variations->max('price') ?? 0;
}
public function getPriceRangeAttribute(): string
{
$min = $this->min_price;
$max = $this->max_price;
if ($min == $max) {
return number_format($min, 0, '.', ' ') . ' ₽';
}
return 'от ' . number_format($min, 0, '.', ' ') . ' ₽ до ' . number_format($max, 0, '.', ' ') . ' ₽';
}
public function getTotalStockAttribute(): int
{
return $this->variations->sum('stock');
}
public function getHasStockAttribute(): bool
{
return $this->total_stock > 0;
}
public function getFullNameAttribute(): string
{
return $this->brand ? "[{$this->brand->name}] {$this->name}" : $this->name;
}
public function scopeActive($query)
{
return $query->where('is_active', true);
}
public function scopeByBrand($query, $brandId)
{
return $query->where('brand_id', $brandId);
}
public function scopeByCategory($query, $categoryId)
{
return $query->where('category_id', $categoryId);
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ProductAttribute extends Model
{
protected $fillable = ['product_id', 'key', 'value'];
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}

View File

@@ -0,0 +1,160 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class ProductVariation extends Model
{
protected $table = 'product_variations';
protected $fillable = [
'product_id',
'sku',
'name',
'price',
'old_price',
'stock',
'is_default',
'is_active',
];
protected $casts = [
'is_default' => 'boolean',
'is_active' => 'boolean',
'price' => 'float',
'old_price' => 'float',
];
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
public function attributes(): HasMany
{
return $this->hasMany(VariationAttribute::class, 'variation_id');
}
public function images(): HasMany
{
return $this->hasMany(VariationImage::class, 'variation_id')
->ordered();
}
/**
* Получить URL главного изображения вариации
*/
public function getMainImageUrlAttribute(): string
{
$image = $this->images()->first();
if ($image) {
return $image->url;
}
return asset('assets/images/products/default.svg');
}
/**
* Получить все изображения вариации
*/
public function getAllImages()
{
return $this->images;
}
public function getHasDiscountAttribute(): bool
{
return $this->old_price && $this->old_price > $this->price;
}
public function getDiscountPercentAttribute(): int
{
if (!$this->has_discount) return 0;
return round(($this->old_price - $this->price) / $this->old_price * 100);
}
public function getInStockAttribute(): bool
{
return $this->stock > 0;
}
public function getFormattedPriceAttribute(): string
{
return number_format($this->price, 0, '.', ' ') . ' ₽';
}
public function getFormattedOldPriceAttribute(): string
{
if (!$this->old_price) return '';
return number_format($this->old_price, 0, '.', ' ') . ' ₽';
}
public static function isSkuUnique($sku, $excludeId = null, $productId = null)
{
$query = self::where('sku', $sku);
if ($excludeId) {
$query->where('id', '!=', $excludeId);
}
if ($productId) {
$query->where('product_id', $productId);
}
return !$query->exists();
}
public function scopeActive($query)
{
return $query->where('is_active', true);
}
public function scopeInStock($query)
{
return $query->where('stock', '>', 0);
}
public function scopeDiscounted($query)
{
return $query->whereNotNull('old_price')
->whereColumn('old_price', '>', 'price');
}
public function scopeDefault($query)
{
return $query->where('is_default', true);
}
// ========== МЕТОДЫ ДЛЯ AJAX ==========
public static function getImagesByVariationId($variationId)
{
$variation = self::with(['images' => function ($query) {
$query->active()->ordered();
}])->find($variationId);
if (!$variation) {
return collect();
}
return $variation->images;
}
public static function getImagesDataById($variationId)
{
$images = self::getImagesByVariationId($variationId);
return $images->map(function ($image) {
return [
'id' => $image->id,
'url' => $image->url,
'sort_order' => $image->sort_order,
'variation_id' => $image->variation_id
];
});
}
}

74
app/Models/Review.php Normal file
View File

@@ -0,0 +1,74 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Review extends Model
{
protected $fillable = [
'user_id',
'product_id',
'rating',
'title',
'comment',
'advantages',
'disadvantages',
'helpful_count',
'unhelpful_count',
'is_approved'
];
protected $casts = [
'is_approved' => 'boolean',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
public function getDateAttribute(): string
{
return $this->created_at->format('d.m.Y');
}
public function getIsFreshAttribute(): bool
{
return $this->created_at->gt(now()->subWeek());
}
public function scopeApproved($query)
{
return $query->where('is_approved', true);
}
public function scopeByRating($query, $rating)
{
return $query->where('rating', $rating);
}
public function scopeHelpful($query)
{
return $query->orderBy('helpful_count', 'desc');
}
public function scopeLatest($query)
{
return $query->orderBy('created_at', 'desc');
}
public function scopeUserProduct($query, $userId, $productId)
{
return $query->where('user_id', $userId)
->where('product_id', $productId);
}
}

32
app/Models/Role.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Role extends Model
{
public $timestamps = false;
protected $fillable = [
'name',
'slug',
'description',
];
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class)->withTimestamps();
}
public function permissions(): BelongsToMany
{
return $this->belongsToMany(Permission::class)->withTimestamps();
}
public function hasPermission(string $permissionSlug): bool
{
return $this->permissions()->where('slug', $permissionSlug)->exists();
}
}

110
app/Models/User.php Normal file
View File

@@ -0,0 +1,110 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'phone',
'role_id',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
public function role(): BelongsTo
{
return $this->belongsTo(Role::class);
}
public function permissions(): BelongsToMany
{
return $this->belongsToMany(Permission::class, 'role_user', 'user_id', 'role_id')
->join('permission_role', 'role_user.role_id', '=', 'permission_role.role_id')
->join('permissions', 'permission_role.permission_id', '=', 'permissions.id')
->select('permissions.*')
->distinct()
->withTimestamps();
}
public function hasRole(string $roleSlug): bool
{
return $this->role()->where('slug', $roleSlug)->exists();
}
public function hasPermission(string $permissionSlug): bool
{
if ($this->hasRole('super_admin')) {
return true;
}
$role = $this->role;
return $role && $role->hasPermission($permissionSlug);
}
public function hasAnyPermission(array $permissionSlugs): bool
{
if ($this->is_super_admin) {
return true;
}
foreach ($permissionSlugs as $permissionSlug) {
if ($this->hasPermission($permissionSlug)) {
return true;
}
}
return false;
}
public function hasAllPermissions(array $permissionSlugs): bool
{
if ($this->is_super_admin) {
return true;
}
foreach ($permissionSlugs as $permissionSlug) {
if (!$this->hasPermission($permissionSlug)) {
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class VariationAttribute extends Model
{
protected $fillable = ['variation_id', 'key', 'value'];
public function variation(): BelongsTo
{
return $this->belongsTo(ProductVariation::class, 'variation_id');
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class VariationImage extends Model
{
public $timestamps = false;
protected $fillable = [
'variation_id',
'path',
'sort_order',
'is_active'
];
protected $casts = [
'sort_order' => 'integer',
'is_active' => 'boolean'
];
public function variation(): BelongsTo
{
return $this->belongsTo(ProductVariation::class, 'variation_id');
}
public function getUrlAttribute(): string
{
if ($this->path && file_exists(public_path($this->path))) {
return asset($this->path);
}
return asset('assets/images/products/default.svg');
}
public function scopeOrdered($query)
{
return $query->orderBy('sort_order', 'asc');
}
public function scopeActive($query)
{
return $query->where('is_active', true);
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Paginator::useBootstrapFive();
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
//
];
/**
* Register any authentication / authorization services.
*/
public function boot(): void
{
Gate::before(function ($user, $ability) {
return $user->hasPermission($ability);
});
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*/
public function boot(): void
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*/
public function shouldDiscoverEvents(): bool
{
return false;
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Http\Controllers\MenuController;
use Illuminate\Support\Facades\View;
class MenuServiceProvider extends ServiceProvider
{
/**
* Register services.
*/
public function register(): void
{
//
}
/**
* Bootstrap services.
*/
public function boot(): void
{
View::composer('*', function ($view) {
$menuController = new MenuController();
$menuData = $menuController->getMenuData();
$view->with('menuCategories', $menuData['categories']);
$view->with('menuContacts', $menuData['contacts']);
$view->with('menuBrands', $menuData['popularBrands']);
$view->with('footerCategories', $menuData['footerCategories']);
});
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to your application's "home" route.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*/
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
}

53
artisan Normal file
View File

@@ -0,0 +1,53 @@
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any of our classes manually. It's great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);

55
bootstrap/app.php Normal file
View File

@@ -0,0 +1,55 @@
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;

2
bootstrap/cache/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore

66
composer.json Normal file
View File

@@ -0,0 +1,66 @@
{
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.1",
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^10.10",
"laravel/sanctum": "^3.3",
"laravel/tinker": "^2.8"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",
"laravel/pint": "^1.0",
"laravel/sail": "^1.18",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^7.0",
"phpunit/phpunit": "^10.1",
"spatie/laravel-ignition": "^2.0"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

8146
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

189
config/app.php Normal file
View File

@@ -0,0 +1,189 @@
<?php
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\ServiceProvider;
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => 'file',
// 'store' => 'redis',
],
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => ServiceProvider::defaultProviders()->merge([
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
App\Providers\MenuServiceProvider::class,
])->toArray(),
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => Facade::defaultAliases()->merge([
// 'Example' => App\Facades\Example::class,
])->toArray(),
];

115
config/auth.php Normal file
View File

@@ -0,0 +1,115 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_reset_tokens',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];

71
config/broadcasting.php Normal file
View File

@@ -0,0 +1,71 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
| Supported: "pusher", "ably", "redis", "log", "null"
|
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
'port' => env('PUSHER_PORT', 443),
'scheme' => env('PUSHER_SCHEME', 'https'),
'encrypted' => true,
'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
],
'client_options' => [
// Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
],
],
'ably' => [
'driver' => 'ably',
'key' => env('ABLY_KEY'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];

111
config/cache.php Normal file
View File

@@ -0,0 +1,111 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
*/
'default' => env('CACHE_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "apc", "array", "database", "file",
| "memcached", "redis", "dynamodb", "octane", "null"
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
'lock_connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
'lock_connection' => 'default',
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, or DynamoDB cache
| stores there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'),
];

34
config/cors.php Normal file
View File

@@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];

151
config/database.php Normal file
View File

@@ -0,0 +1,151 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],
];

76
config/filesystems.php Normal file
View File

@@ -0,0 +1,76 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been set up for each driver as an example of the required values.
|
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'throw' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

54
config/hashing.php Normal file
View File

@@ -0,0 +1,54 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Hash Driver
|--------------------------------------------------------------------------
|
| This option controls the default hash driver that will be used to hash
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon", "argon2id"
|
*/
'driver' => 'bcrypt',
/*
|--------------------------------------------------------------------------
| Bcrypt Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Bcrypt algorithm. This will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 12),
'verify' => true,
],
/*
|--------------------------------------------------------------------------
| Argon Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Argon algorithm. These will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'argon' => [
'memory' => 65536,
'threads' => 1,
'time' => 4,
'verify' => true,
],
];

131
config/logging.php Normal file
View File

@@ -0,0 +1,131 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => false,
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => 14,
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => LOG_USER,
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

134
config/mail.php Normal file
View File

@@ -0,0 +1,134 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send any email
| messages sent by your application. Alternative mailers may be setup
| and used as needed; however, this mailer will be used by default.
|
*/
'default' => env('MAIL_MAILER', 'smtp'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers to be used while
| sending an e-mail. You will specify which one you are using for your
| mailers below. You are free to add additional mailers as required.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "log", "array", "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN'),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => null,
// 'client' => [
// 'timeout' => 5,
// ],
],
'mailgun' => [
'transport' => 'mailgun',
// 'client' => [
// 'timeout' => 5,
// ],
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];

109
config/queue.php Normal file
View File

@@ -0,0 +1,109 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue API supports an assortment of back-ends via a single
| API, giving you convenient access to each back-end using the same
| syntax for every one. Here you may define a default connection.
|
*/
'default' => env('QUEUE_CONNECTION', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
'after_commit' => false,
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
];

83
config/sanctum.php Normal file
View File

@@ -0,0 +1,83 @@
<?php
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort()
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
],
];

34
config/services.php Normal file
View File

@@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
'scheme' => 'https',
],
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
];

214
config/session.php Normal file
View File

@@ -0,0 +1,214 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| While using one of the framework's cache driven session backends you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" since this is a secure default value.
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => 'lax',
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => false,
];

36
config/view.php Normal file
View File

@@ -0,0 +1,36 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => [
resource_path('views'),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => env(
'VIEW_COMPILED_PATH',
realpath(storage_path('framework/views'))
),
];

1
database/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
*.sqlite*

View File

@@ -0,0 +1,44 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

View File

@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};

View File

@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('password_reset_tokens');
}
};

View File

@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('failed_jobs');
}
};

View File

@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->string('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

View File

@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('description')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('roles');
}
};

View File

@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('permissions', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('group')->nullable();
$table->text('description')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('permissions');
}
};

View File

@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('permission_role', function (Blueprint $table) {
$table->id();
$table->foreignId('permission_id')->constrained()->onDelete('cascade');
$table->foreignId('role_id')->constrained()->onDelete('cascade');
$table->timestamps();
$table->unique(['permission_id', 'role_id']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('permission_role');
}
};

View File

@@ -0,0 +1,45 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->text('description')->nullable();
$table->string('icon')->nullable();
$table->string('image')->nullable();
$table->unsignedBigInteger('parent_id')->nullable();
$table->integer('sort_order')->default(0)->index();
$table->boolean('is_active')->default(true);
$table->index('parent_id');
$table->foreign('parent_id')
->references('id')
->on('categories')
->onDelete('cascade');
$table->unique(['name', 'parent_id']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('categories');
}
};

View File

@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('brands', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->text('description')->nullable();
$table->string('logo')->nullable();
$table->string('website')->nullable();
$table->string('country')->nullable();
$table->boolean('is_active')->default(true);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('brands');
}
};

View File

@@ -0,0 +1,40 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->text('description');
$table->foreignId('brand_id')->nullable()->constrained()->onDelete('set null');
$table->foreignId('category_id')->constrained()->onDelete('cascade');
$table->json('attributes')->nullable();
$table->boolean('is_active')->default(true);
$table->timestamps();
$table->index('brand_id');
$table->index('category_id');
$table->index('is_active');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};

View File

@@ -0,0 +1,44 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('product_variations', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->string('sku')->unique();
$table->decimal('price', 10, 2);
$table->decimal('old_price', 10, 2)->nullable();
$table->json('attributes')->nullable();
$table->json('images')->nullable();
$table->integer('stock')->default(0);
$table->boolean('is_default')->default(false);
$table->boolean('is_active')->default(true);
$table->timestamps();
$table->index('sku');
$table->index('product_id');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('product_variations');
}
};

View File

@@ -0,0 +1,43 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('reviews', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('product_id')->constrained()->onDelete('cascade');
$table->tinyInteger('rating');
$table->string('title')->nullable();
$table->text('comment');
$table->text('advantages')->nullable();
$table->text('disadvantages')->nullable();
$table->integer('helpful_count')->default(0);
$table->integer('unhelpful_count')->default(0);
$table->boolean('is_approved')->default(false);
$table->timestamps();
$table->index('rating');
$table->index('is_approved');
$table->index('created_at');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('reviews');
}
};

View File

@@ -0,0 +1,45 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->string('name')->default('Хвостики и лапки');
$table->string('description')->nullable();
$table->string('logo')->nullable();
$table->string('favicon')->nullable();
$table->string('phone')->nullable();
$table->string('email')->nullable();
$table->string('address')->nullable();
$table->string('work_hours')->nullable();
$table->string('telegram')->nullable();
$table->string('whatsapp')->nullable();
$table->string('vkontakte')->nullable();
$table->string('meta_title')->nullable();
$table->text('meta_description')->nullable();
$table->text('meta_keywords')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('contacts');
}
};

View File

@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('products', function (Blueprint $table) {
$table->string('meta_title')->nullable()->after('is_active');
$table->text('meta_description')->nullable()->after('meta_title');
$table->string('meta_keywords')->nullable()->after('meta_description');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn(['meta_title', 'meta_description', 'meta_keywords']);
});
}
};

View File

@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->string('phone', 20)->nullable()->after('email');
$table->index('phone');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('phone');
});
}
};

Some files were not shown because too many files have changed in this diff Show More