Initial commit

This commit is contained in:
2026-03-24 17:01:12 +00:00
commit a88504357d
237 changed files with 34375 additions and 0 deletions

18
src/.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

66
src/.env.example Normal file
View File

@@ -0,0 +1,66 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_TIMEZONE=UTC
APP_URL=http://localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=sqlite
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=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
VITE_APP_NAME="${APP_NAME}"

64
src/.env.mysql Normal file
View File

@@ -0,0 +1,64 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_TIMEZONE=UTC
APP_URL=http://localhost:8080
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
APP_MAINTENANCE_STORE=database
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=secret
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=redis
CACHE_STORE=redis
CACHE_PREFIX=laravel_cache
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=redis
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
VITE_APP_NAME="${APP_NAME}"

64
src/.env.pgsql Normal file
View File

@@ -0,0 +1,64 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_TIMEZONE=UTC
APP_URL=http://localhost:8080
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
APP_MAINTENANCE_STORE=database
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=pgsql
DB_HOST=pgsql
DB_PORT=5432
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=secret
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=redis
CACHE_STORE=redis
CACHE_PREFIX=laravel_cache
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=redis
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
VITE_APP_NAME="${APP_NAME}"

60
src/.env.sqlite Normal file
View File

@@ -0,0 +1,60 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_TIMEZONE=UTC
APP_URL=http://localhost:8080
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
APP_MAINTENANCE_STORE=database
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=sqlite
DB_DATABASE=/var/www/html/database/database.sqlite
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=redis
CACHE_STORE=redis
CACHE_PREFIX=laravel_cache
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=redis
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
VITE_APP_NAME="${APP_NAME}"

11
src/.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

23
src/.gitignore vendored Normal file
View File

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

66
src/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).

View File

@@ -0,0 +1,71 @@
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class MakeAdminCommand extends Command
{
protected $signature = 'make:admin
{email : The email address for the admin user}
{--name= : The name for the admin user}
{--password= : The password (will prompt if not provided)}';
protected $description = 'Create a new admin user with full permissions';
public function handle(): int
{
$email = $this->argument('email');
$name = $this->option('name') ?? $this->ask('Enter admin name', 'Admin');
$password = $this->option('password') ?? $this->secret('Enter password');
// Validate email
$validator = Validator::make(
['email' => $email],
['email' => 'required|email|unique:users,email']
);
if ($validator->fails()) {
$this->error('Validation failed:');
foreach ($validator->errors()->all() as $error) {
$this->error(" - {$error}");
}
return Command::FAILURE;
}
// Validate password
if (strlen($password) < 8) {
$this->error('Password must be at least 8 characters.');
return Command::FAILURE;
}
// Create user
$user = User::create([
'name' => $name,
'email' => $email,
'password' => Hash::make($password),
'email_verified_at' => now(),
]);
// Assign admin role
$user->assignRole('admin');
$this->info("✅ Admin user created successfully!");
$this->table(
['Field', 'Value'],
[
['Name', $name],
['Email', $email],
['Role', 'admin'],
]
);
$this->newLine();
$this->info("Login at: /admin");
return Command::SUCCESS;
}
}

View File

@@ -0,0 +1,597 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
class MakeModuleCommand extends Command
{
protected $signature = 'make:module
{name : The name of the module (PascalCase)}
{--model= : Create a model with the given name}
{--api : Include API routes}
{--no-filament : Skip Filament resource generation}';
protected $description = 'Create a new module with full structure (ServiceProvider, Config, Routes, Views, Permissions)';
protected string $studlyName;
protected string $kebabName;
protected string $snakeName;
protected string $modulePath;
protected ?string $modelName;
public function handle(): int
{
$name = $this->argument('name');
$this->studlyName = Str::studly($name);
$this->kebabName = Str::kebab($name);
$this->snakeName = Str::snake($name);
$this->modelName = $this->option('model') ? Str::studly($this->option('model')) : null;
$this->modulePath = app_path("Modules/{$this->studlyName}");
if (File::exists($this->modulePath)) {
$this->error("Module {$this->studlyName} already exists!");
return self::FAILURE;
}
$this->info("Creating module: {$this->studlyName}");
$this->newLine();
$this->createDirectoryStructure();
$this->createServiceProvider();
$this->createConfig();
$this->createPermissions();
$this->createController();
$this->createRoutes();
$this->createViews();
if ($this->modelName) {
$this->createModel();
$this->createMigration();
if (!$this->option('no-filament')) {
$this->createFilamentResource();
}
}
$this->createTests();
$this->registerServiceProvider();
$this->newLine();
$this->info("✅ Module {$this->studlyName} created successfully!");
$this->newLine();
$this->warn("Next steps:");
$this->line(" 1. Run migrations: <info>php artisan migrate</info>");
$this->line(" 2. Seed permissions: <info>php artisan db:seed --class=RolePermissionSeeder</info>");
$this->line(" 3. Clear caches: <info>php artisan optimize:clear</info>");
$this->newLine();
$this->line(" Access at:");
$this->line(" - Frontend: <info>/{$this->kebabName}</info>");
if ($this->modelName && !$this->option('no-filament')) {
$this->line(" - Admin: <info>/admin → {$this->studlyName}</info>");
}
if ($this->option('api')) {
$this->line(" - API: <info>/api/{$this->kebabName}</info>");
}
return self::SUCCESS;
}
protected function createDirectoryStructure(): void
{
$directories = [
'',
'/Config',
'/Database/Migrations',
'/Database/Seeders',
'/Filament/Resources',
'/Http/Controllers',
'/Http/Middleware',
'/Http/Requests',
'/Models',
'/Policies',
'/Services',
'/Routes',
'/Resources/views',
];
foreach ($directories as $dir) {
File::makeDirectory("{$this->modulePath}{$dir}", 0755, true);
}
$this->info("✓ Created directory structure");
}
protected function createServiceProvider(): void
{
$stub = <<<PHP
<?php
namespace App\Modules\\{$this->studlyName};
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Route;
class {$this->studlyName}ServiceProvider extends ServiceProvider
{
public function register(): void
{
\$this->mergeConfigFrom(
__DIR__ . '/Config/{$this->snakeName}.php',
'{$this->snakeName}'
);
}
public function boot(): void
{
\$this->loadMigrationsFrom(__DIR__ . '/Database/Migrations');
\$this->loadViewsFrom(__DIR__ . '/Resources/views', '{$this->kebabName}');
\$this->registerRoutes();
\$this->registerPermissions();
}
protected function registerRoutes(): void
{
Route::middleware(['web', 'auth'])
->prefix('{$this->kebabName}')
->name('{$this->kebabName}.')
->group(__DIR__ . '/Routes/web.php');
if (file_exists(__DIR__ . '/Routes/api.php')) {
Route::middleware(['api', 'auth:sanctum'])
->prefix('api/{$this->kebabName}')
->name('api.{$this->kebabName}.')
->group(__DIR__ . '/Routes/api.php');
}
}
protected function registerPermissions(): void
{
// Permissions are registered via RolePermissionSeeder
// See: Permissions.php in this module
}
}
PHP;
File::put("{$this->modulePath}/{$this->studlyName}ServiceProvider.php", $stub);
$this->info("✓ Created ServiceProvider");
}
protected function createConfig(): void
{
$stub = <<<PHP
<?php
return [
'name' => '{$this->studlyName}',
'slug' => '{$this->kebabName}',
'version' => '1.0.0',
'audit' => [
'enabled' => true,
'strategy' => 'all', // 'all', 'include', 'exclude', 'none'
'include' => [],
'exclude' => [],
],
];
PHP;
File::put("{$this->modulePath}/Config/{$this->snakeName}.php", $stub);
$this->info("✓ Created Config");
}
protected function createPermissions(): void
{
$stub = <<<PHP
<?php
return [
'{$this->snakeName}.view' => 'View {$this->studlyName}',
'{$this->snakeName}.create' => 'Create {$this->studlyName} records',
'{$this->snakeName}.edit' => 'Edit {$this->studlyName} records',
'{$this->snakeName}.delete' => 'Delete {$this->studlyName} records',
];
PHP;
File::put("{$this->modulePath}/Permissions.php", $stub);
$this->info("✓ Created Permissions");
}
protected function createController(): void
{
$stub = <<<PHP
<?php
namespace App\Modules\\{$this->studlyName}\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class {$this->studlyName}Controller extends Controller
{
public function index()
{
\$this->authorize('{$this->snakeName}.view');
return view('{$this->kebabName}::index');
}
}
PHP;
File::put("{$this->modulePath}/Http/Controllers/{$this->studlyName}Controller.php", $stub);
$this->info("✓ Created Controller");
}
protected function createRoutes(): void
{
// Web routes
$webStub = <<<PHP
<?php
use App\Modules\\{$this->studlyName}\Http\Controllers\\{$this->studlyName}Controller;
use Illuminate\Support\Facades\Route;
Route::get('/', [{$this->studlyName}Controller::class, 'index'])->name('index');
PHP;
File::put("{$this->modulePath}/Routes/web.php", $webStub);
// API routes (if requested)
if ($this->option('api')) {
$apiStub = <<<PHP
<?php
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->group(function () {
// API routes here
});
PHP;
File::put("{$this->modulePath}/Routes/api.php", $apiStub);
}
$this->info("✓ Created Routes" . ($this->option('api') ? ' (web + api)' : ''));
}
protected function createViews(): void
{
$stub = <<<BLADE
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
{{ __('{$this->studlyName}') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 text-gray-900 dark:text-gray-100">
{{ __('{$this->studlyName} module is working!') }}
</div>
</div>
</div>
</div>
</x-app-layout>
BLADE;
File::put("{$this->modulePath}/Resources/views/index.blade.php", $stub);
$this->info("✓ Created Views");
}
protected function createModel(): void
{
$tableName = Str::snake(Str::plural($this->modelName));
$stub = <<<PHP
<?php
namespace App\Modules\\{$this->studlyName}\Models;
use App\Traits\ModuleAuditable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Contracts\Auditable;
class {$this->modelName} extends Model implements Auditable
{
use HasFactory, ModuleAuditable;
protected \$table = '{$tableName}';
protected \$fillable = [
'name',
'description',
];
protected \$casts = [
//
];
}
PHP;
File::put("{$this->modulePath}/Models/{$this->modelName}.php", $stub);
$this->info("✓ Created Model: {$this->modelName}");
}
protected function createMigration(): void
{
$tableName = Str::snake(Str::plural($this->modelName));
$timestamp = date('Y_m_d_His');
$migrationName = "create_{$tableName}_table";
$stub = <<<PHP
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('{$tableName}', function (Blueprint \$table) {
\$table->id();
\$table->string('name');
\$table->text('description')->nullable();
\$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('{$tableName}');
}
};
PHP;
$migrationPath = "{$this->modulePath}/Database/Migrations/{$timestamp}_{$migrationName}.php";
File::put($migrationPath, $stub);
$this->info("✓ Created Migration: {$migrationName}");
}
protected function createFilamentResource(): void
{
$modelClass = "App\\Modules\\{$this->studlyName}\\Models\\{$this->modelName}";
$tableName = Str::snake(Str::plural($this->modelName));
// Create the resource
$resourceStub = <<<PHP
<?php
namespace App\Modules\\{$this->studlyName}\Filament\Resources;
use App\Modules\\{$this->studlyName}\Filament\Resources\\{$this->modelName}Resource\Pages;
use App\Modules\\{$this->studlyName}\Models\\{$this->modelName};
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
class {$this->modelName}Resource extends Resource
{
protected static ?string \$model = {$this->modelName}::class;
protected static ?string \$navigationIcon = 'heroicon-o-rectangle-stack';
protected static ?string \$navigationGroup = '{$this->studlyName}';
protected static ?int \$navigationSort = 1;
public static function canAccess(): bool
{
return auth()->user()?->can('{$this->snakeName}.view') ?? false;
}
public static function form(Form \$form): Form
{
return \$form
->schema([
Forms\Components\Section::make('{$this->modelName} Details')
->schema([
Forms\Components\TextInput::make('name')
->required()
->maxLength(255),
Forms\Components\Textarea::make('description')
->rows(3),
]),
]);
}
public static function table(Table \$table): Table
{
return \$table
->columns([
Tables\Columns\TextColumn::make('name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('description')
->limit(50),
Tables\Columns\TextColumn::make('created_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\List{$this->modelName}s::route('/'),
'create' => Pages\Create{$this->modelName}::route('/create'),
'edit' => Pages\Edit{$this->modelName}::route('/{record}/edit'),
];
}
}
PHP;
File::put("{$this->modulePath}/Filament/Resources/{$this->modelName}Resource.php", $resourceStub);
// Create Pages directory
File::makeDirectory("{$this->modulePath}/Filament/Resources/{$this->modelName}Resource/Pages", 0755, true);
// Create List page
$listStub = <<<PHP
<?php
namespace App\Modules\\{$this->studlyName}\Filament\Resources\\{$this->modelName}Resource\Pages;
use App\Modules\\{$this->studlyName}\Filament\Resources\\{$this->modelName}Resource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class List{$this->modelName}s extends ListRecords
{
protected static string \$resource = {$this->modelName}Resource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}
PHP;
File::put("{$this->modulePath}/Filament/Resources/{$this->modelName}Resource/Pages/List{$this->modelName}s.php", $listStub);
// Create Create page
$createStub = <<<PHP
<?php
namespace App\Modules\\{$this->studlyName}\Filament\Resources\\{$this->modelName}Resource\Pages;
use App\Modules\\{$this->studlyName}\Filament\Resources\\{$this->modelName}Resource;
use Filament\Resources\Pages\CreateRecord;
class Create{$this->modelName} extends CreateRecord
{
protected static string \$resource = {$this->modelName}Resource::class;
}
PHP;
File::put("{$this->modulePath}/Filament/Resources/{$this->modelName}Resource/Pages/Create{$this->modelName}.php", $createStub);
// Create Edit page
$editStub = <<<PHP
<?php
namespace App\Modules\\{$this->studlyName}\Filament\Resources\\{$this->modelName}Resource\Pages;
use App\Modules\\{$this->studlyName}\Filament\Resources\\{$this->modelName}Resource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class Edit{$this->modelName} extends EditRecord
{
protected static string \$resource = {$this->modelName}Resource::class;
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}
PHP;
File::put("{$this->modulePath}/Filament/Resources/{$this->modelName}Resource/Pages/Edit{$this->modelName}.php", $editStub);
$this->info("✓ Created Filament Resource: {$this->modelName}Resource");
}
protected function createTests(): void
{
$testPath = base_path("tests/Feature/Modules/{$this->studlyName}");
File::makeDirectory($testPath, 0755, true);
$stub = <<<PHP
<?php
namespace Tests\Feature\Modules\\{$this->studlyName};
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class {$this->studlyName}Test extends TestCase
{
use RefreshDatabase;
public function test_user_can_view_{$this->snakeName}_index(): void
{
\$user = User::factory()->create();
\$user->givePermissionTo('{$this->snakeName}.view');
\$response = \$this->actingAs(\$user)
->get('/{$this->kebabName}');
\$response->assertStatus(200);
}
public function test_unauthorized_user_cannot_view_{$this->snakeName}(): void
{
\$user = User::factory()->create();
\$response = \$this->actingAs(\$user)
->get('/{$this->kebabName}');
\$response->assertStatus(403);
}
}
PHP;
File::put("{$testPath}/{$this->studlyName}Test.php", $stub);
$this->info("✓ Created Tests");
}
protected function registerServiceProvider(): void
{
$providersPath = base_path('bootstrap/providers.php');
if (File::exists($providersPath)) {
$content = File::get($providersPath);
$providerClass = "App\\Modules\\{$this->studlyName}\\{$this->studlyName}ServiceProvider::class";
if (!str_contains($content, $providerClass)) {
// Add the provider before the closing bracket
$content = preg_replace(
'/(\];)/',
" {$providerClass},\n$1",
$content
);
File::put($providersPath, $content);
$this->info("✓ Registered ServiceProvider in bootstrap/providers.php");
}
} else {
$this->warn("⚠ Could not auto-register ServiceProvider. Add manually to config/app.php:");
$this->line(" App\\Modules\\{$this->studlyName}\\{$this->studlyName}ServiceProvider::class");
}
}
}

View File

@@ -0,0 +1,186 @@
<?php
namespace App\Filament\Pages;
use App\Services\ModuleDiscoveryService;
use App\Services\ModuleGeneratorService;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Illuminate\Support\Str;
class ModuleGenerator extends Page implements HasForms
{
use InteractsWithForms;
protected static ?string $navigationIcon = 'heroicon-o-cube';
protected static ?string $navigationLabel = 'Module Generator';
protected static ?string $navigationGroup = 'Development';
protected static ?int $navigationSort = 100;
protected static string $view = 'filament.pages.module-generator';
public ?array $data = [];
public ?array $result = null;
public array $modules = [];
public array $summary = [];
public ?string $expandedModule = null;
public static function canAccess(): bool
{
// Only available in local environment
return app()->environment('local');
}
public static function shouldRegisterNavigation(): bool
{
return app()->environment('local');
}
public function mount(): void
{
$this->form->fill([
'create_git_branch' => true,
'include_api' => false,
]);
$this->loadModules();
}
public function loadModules(): void
{
$discovery = new ModuleDiscoveryService();
$this->modules = $discovery->discoverModules();
$this->summary = $discovery->getModuleSummary();
}
public function toggleModule(string $moduleName): void
{
$this->expandedModule = $this->expandedModule === $moduleName ? null : $moduleName;
}
public function form(Form $form): Form
{
return $form
->schema([
Section::make('Module Details')
->description('Create a new module skeleton with all the necessary folders and files.')
->schema([
TextInput::make('name')
->label('Module Name')
->placeholder('e.g., Accounting, Inventory, HumanResources')
->helperText('Use PascalCase. This will create app/Modules/YourModuleName/')
->required()
->maxLength(50)
->rules(['regex:/^[A-Z][a-zA-Z0-9]*$/'])
->validationMessages([
'regex' => 'Module name must be PascalCase (start with uppercase, letters and numbers only).',
])
->live(onBlur: true)
->afterStateUpdated(fn ($state, callable $set) =>
$set('name', Str::studly($state))
),
Textarea::make('description')
->label('Description')
->placeholder('Brief description of what this module does...')
->rows(2)
->maxLength(255),
]),
Section::make('Options')
->schema([
Toggle::make('create_git_branch')
->label('Create Git Branch')
->helperText('Automatically create and checkout a new branch: module/{module-name}')
->default(true),
Toggle::make('include_api')
->label('Include API Routes')
->helperText('Add Routes/api.php with Sanctum authentication')
->default(false),
])
->columns(2),
Section::make('What Will Be Created')
->schema([
\Filament\Forms\Components\Placeholder::make('structure')
->label('')
->content(fn () => new \Illuminate\Support\HtmlString('
<div class="text-sm text-gray-600 dark:text-gray-400 font-mono bg-gray-50 dark:bg-gray-900 p-4 rounded-lg">
<div class="font-bold mb-2">app/Modules/{ModuleName}/</div>
<div class="ml-4">
├── Config/{module_name}.php<br>
├── Database/Migrations/<br>
├── Database/Seeders/<br>
├── Filament/Resources/<br>
├── Http/Controllers/{ModuleName}Controller.php<br>
├── Http/Middleware/<br>
├── Http/Requests/<br>
├── Models/<br>
├── Policies/<br>
├── Services/<br>
├── Routes/web.php<br>
├── Resources/views/index.blade.php<br>
├── Permissions.php<br>
├── {ModuleName}ServiceProvider.php<br>
└── README.md
</div>
</div>
')),
])
->collapsible()
->collapsed(),
])
->statePath('data');
}
public function generate(): void
{
$data = $this->form->getState();
$service = new ModuleGeneratorService();
$this->result = $service->generate($data['name'], [
'description' => $data['description'] ?? '',
'create_git_branch' => $data['create_git_branch'] ?? true,
'include_api' => $data['include_api'] ?? false,
]);
if ($this->result['success']) {
Notification::make()
->title('Module Created Successfully!')
->body("Module {$this->result['module_name']} has been created.")
->success()
->persistent()
->send();
// Reset form for next module
$this->form->fill([
'name' => '',
'description' => '',
'create_git_branch' => true,
'include_api' => false,
]);
// Reload modules list
$this->loadModules();
} else {
Notification::make()
->title('Module Creation Failed')
->body($this->result['message'])
->danger()
->persistent()
->send();
}
}
public function clearResult(): void
{
$this->result = null;
}
}

View File

@@ -0,0 +1,132 @@
<?php
namespace App\Filament\Pages;
use App\Models\Setting;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Pages\Page;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
class Settings extends Page
{
protected static ?string $navigationIcon = 'heroicon-o-cog-6-tooth';
protected static string $view = 'filament.pages.settings';
protected static ?string $navigationGroup = 'Settings';
protected static ?int $navigationSort = 99;
public ?array $data = [];
public function mount(): void
{
$siteName = Setting::get('site_name', config('app.name'));
$siteLogo = Setting::get('site_logo');
$primaryColor = Setting::get('primary_color', '#3b82f6');
$secondaryColor = Setting::get('secondary_color', '#8b5cf6');
$accentColor = Setting::get('accent_color', '#10b981');
$siteDescription = Setting::get('site_description');
$contactEmail = Setting::get('contact_email');
$maintenanceMode = Setting::get('maintenance_mode', false);
$enableRegistration = Setting::get('enable_registration', false);
$this->form->fill([
'site_name' => is_string($siteName) ? $siteName : config('app.name'),
'site_logo' => is_string($siteLogo) || is_null($siteLogo) ? $siteLogo : null,
'primary_color' => is_string($primaryColor) ? $primaryColor : '#3b82f6',
'secondary_color' => is_string($secondaryColor) ? $secondaryColor : '#8b5cf6',
'accent_color' => is_string($accentColor) ? $accentColor : '#10b981',
'site_description' => is_string($siteDescription) || is_null($siteDescription) ? $siteDescription : '',
'contact_email' => is_string($contactEmail) || is_null($contactEmail) ? $contactEmail : '',
'maintenance_mode' => is_bool($maintenanceMode) ? $maintenanceMode : false,
'enable_registration' => is_bool($enableRegistration) ? $enableRegistration : false,
]);
}
public function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Section::make('General Settings')
->schema([
Forms\Components\TextInput::make('site_name')
->label('Site Name')
->required()
->maxLength(255),
Forms\Components\FileUpload::make('site_logo')
->label('Site Logo')
->image()
->directory('logos')
->visibility('public'),
Forms\Components\Textarea::make('site_description')
->label('Site Description')
->rows(3)
->maxLength(500),
Forms\Components\TextInput::make('contact_email')
->label('Contact Email')
->email()
->maxLength(255),
]),
Forms\Components\Section::make('Color Scheme')
->schema([
Forms\Components\ColorPicker::make('primary_color')
->label('Primary Color'),
Forms\Components\ColorPicker::make('secondary_color')
->label('Secondary Color'),
Forms\Components\ColorPicker::make('accent_color')
->label('Accent Color'),
])
->columns(3),
Forms\Components\Section::make('System')
->schema([
Forms\Components\Toggle::make('enable_registration')
->label('Enable User Registration')
->helperText('Allow new users to register. When disabled, only admins can create users.'),
Forms\Components\Toggle::make('maintenance_mode')
->label('Maintenance Mode')
->helperText('Enable to put the site in maintenance mode'),
]),
])
->statePath('data');
}
protected function getFormActions(): array
{
return [
Action::make('save')
->label('Save Settings')
->submit('save'),
];
}
public function save(): void
{
$data = $this->form->getState();
Setting::set('site_name', $data['site_name'] ?? '');
Setting::set('site_logo', $data['site_logo'] ?? '');
Setting::set('primary_color', $data['primary_color'] ?? '#3b82f6');
Setting::set('secondary_color', $data['secondary_color'] ?? '#8b5cf6');
Setting::set('accent_color', $data['accent_color'] ?? '#10b981');
Setting::set('site_description', $data['site_description'] ?? '');
Setting::set('contact_email', $data['contact_email'] ?? '');
Setting::set('maintenance_mode', $data['maintenance_mode'] ?? false, 'boolean');
Setting::set('enable_registration', $data['enable_registration'] ?? false, 'boolean');
Notification::make()
->title('Settings saved successfully')
->success()
->send();
}
}

View File

@@ -0,0 +1,231 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\AuditResource\Pages;
use App\Models\Audit;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Infolists;
use Filament\Infolists\Infolist;
use Illuminate\Database\Eloquent\Builder;
class AuditResource extends Resource
{
protected static ?string $model = Audit::class;
protected static ?string $navigationIcon = 'heroicon-o-clipboard-document-list';
protected static ?string $navigationGroup = 'System';
protected static ?string $navigationLabel = 'Audit Trail';
protected static ?int $navigationSort = 100;
protected static ?string $modelLabel = 'Audit Log';
protected static ?string $pluralModelLabel = 'Audit Trail';
public static function canAccess(): bool
{
return auth()->user()?->can('audit.view') ?? false;
}
public static function canCreate(): bool
{
return false;
}
public static function canEdit($record): bool
{
return false;
}
public static function canDelete($record): bool
{
return false;
}
public static function form(Form $form): Form
{
return $form->schema([]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('created_at')
->label('Date/Time')
->dateTime('M j, Y H:i:s')
->sortable(),
Tables\Columns\TextColumn::make('user.name')
->label('User')
->default('System')
->searchable()
->sortable(),
Tables\Columns\BadgeColumn::make('event')
->label('Action')
->colors([
'success' => 'created',
'warning' => 'updated',
'danger' => 'deleted',
'info' => 'restored',
])
->formatStateUsing(fn (string $state): string => ucfirst($state)),
Tables\Columns\TextColumn::make('auditable_type')
->label('Model')
->formatStateUsing(fn (string $state): string => class_basename($state))
->sortable(),
Tables\Columns\TextColumn::make('auditable_id')
->label('Record ID')
->sortable(),
Tables\Columns\TextColumn::make('ip_address')
->label('IP Address')
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('url')
->label('URL')
->limit(30)
->toggleable(isToggledHiddenByDefault: true),
])
->defaultSort('created_at', 'desc')
->filters([
Tables\Filters\SelectFilter::make('event')
->label('Action')
->options([
'created' => 'Created',
'updated' => 'Updated',
'deleted' => 'Deleted',
'restored' => 'Restored',
]),
Tables\Filters\SelectFilter::make('user_id')
->label('User')
->relationship('user', 'name')
->searchable()
->preload(),
Tables\Filters\SelectFilter::make('auditable_type')
->label('Model')
->options(fn () => Audit::query()
->distinct()
->pluck('auditable_type')
->mapWithKeys(fn ($type) => [$type => class_basename($type)])
->toArray()
),
Tables\Filters\Filter::make('created_at')
->form([
Forms\Components\DatePicker::make('from')
->label('From Date'),
Forms\Components\DatePicker::make('until')
->label('Until Date'),
])
->query(function (Builder $query, array $data): Builder {
return $query
->when(
$data['from'],
fn (Builder $query, $date): Builder => $query->whereDate('created_at', '>=', $date),
)
->when(
$data['until'],
fn (Builder $query, $date): Builder => $query->whereDate('created_at', '<=', $date),
);
})
->indicateUsing(function (array $data): array {
$indicators = [];
if ($data['from'] ?? null) {
$indicators['from'] = 'From: ' . $data['from'];
}
if ($data['until'] ?? null) {
$indicators['until'] = 'Until: ' . $data['until'];
}
return $indicators;
}),
])
->actions([
Tables\Actions\ViewAction::make(),
])
->bulkActions([])
->poll('60s');
}
public static function infolist(Infolist $infolist): Infolist
{
return $infolist
->schema([
Infolists\Components\Section::make('Audit Details')
->schema([
Infolists\Components\Grid::make(3)
->schema([
Infolists\Components\TextEntry::make('created_at')
->label('Date/Time')
->dateTime('F j, Y H:i:s'),
Infolists\Components\TextEntry::make('user.name')
->label('User')
->default('System'),
Infolists\Components\TextEntry::make('event')
->label('Action')
->badge()
->color(fn (string $state): string => match ($state) {
'created' => 'success',
'updated' => 'warning',
'deleted' => 'danger',
'restored' => 'info',
default => 'gray',
})
->formatStateUsing(fn (string $state): string => ucfirst($state)),
]),
Infolists\Components\Grid::make(3)
->schema([
Infolists\Components\TextEntry::make('auditable_type')
->label('Model')
->formatStateUsing(fn (string $state): string => class_basename($state)),
Infolists\Components\TextEntry::make('auditable_id')
->label('Record ID'),
Infolists\Components\TextEntry::make('ip_address')
->label('IP Address')
->default('N/A'),
]),
Infolists\Components\TextEntry::make('url')
->label('URL')
->columnSpanFull(),
]),
Infolists\Components\Section::make('Changes')
->schema([
Infolists\Components\ViewEntry::make('changes')
->view('filament.infolists.entries.audit-changes')
->columnSpanFull(),
]),
]);
}
public static function getRelations(): array
{
return [];
}
public static function getPages(): array
{
return [
'index' => Pages\ListAudits::route('/'),
'view' => Pages\ViewAudit::route('/{record}'),
];
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace App\Filament\Resources\AuditResource\Pages;
use App\Filament\Resources\AuditResource;
use Filament\Resources\Pages\ListRecords;
class ListAudits extends ListRecords
{
protected static string $resource = AuditResource::class;
protected function getHeaderActions(): array
{
return [];
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace App\Filament\Resources\AuditResource\Pages;
use App\Filament\Resources\AuditResource;
use Filament\Resources\Pages\ViewRecord;
class ViewAudit extends ViewRecord
{
protected static string $resource = AuditResource::class;
protected function getHeaderActions(): array
{
return [];
}
}

View File

@@ -0,0 +1,146 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\MenuResource\Pages;
use App\Filament\Resources\MenuResource\RelationManagers;
use App\Models\Menu;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Str;
class MenuResource extends Resource
{
protected static ?string $model = Menu::class;
protected static ?string $navigationIcon = 'heroicon-o-bars-3';
protected static ?string $navigationGroup = 'Settings';
protected static ?int $navigationSort = 10;
public static function canAccess(): bool
{
$user = auth()->user();
return $user?->hasRole('admin') || $user?->can('menus.view');
}
public static function canCreate(): bool
{
$user = auth()->user();
return $user?->hasRole('admin') || $user?->can('menus.create');
}
public static function canEdit($record): bool
{
$user = auth()->user();
return $user?->hasRole('admin') || $user?->can('menus.edit');
}
public static function canDelete($record): bool
{
$user = auth()->user();
return $user?->hasRole('admin') || $user?->can('menus.delete');
}
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Section::make('Menu Details')
->schema([
Forms\Components\TextInput::make('name')
->required()
->maxLength(255)
->live(onBlur: true)
->afterStateUpdated(fn ($state, Forms\Set $set) =>
$set('slug', Str::slug($state))
),
Forms\Components\TextInput::make('slug')
->required()
->maxLength(255)
->unique(ignoreRecord: true),
Forms\Components\Select::make('location')
->options([
'header' => 'Header Navigation',
'footer' => 'Footer Navigation',
'sidebar' => 'Sidebar Navigation',
])
->placeholder('Select a location'),
Forms\Components\Toggle::make('is_active')
->label('Active')
->default(true),
])->columns(2),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('slug')
->searchable()
->badge()
->color('gray'),
Tables\Columns\TextColumn::make('location')
->badge()
->color(fn (?string $state) => match ($state) {
'header' => 'success',
'footer' => 'warning',
'sidebar' => 'info',
default => 'gray',
}),
Tables\Columns\TextColumn::make('allItems_count')
->label('Items')
->counts('allItems')
->badge(),
Tables\Columns\IconColumn::make('is_active')
->label('Active')
->boolean(),
Tables\Columns\TextColumn::make('updated_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
Tables\Filters\SelectFilter::make('location')
->options([
'header' => 'Header',
'footer' => 'Footer',
'sidebar' => 'Sidebar',
]),
Tables\Filters\TernaryFilter::make('is_active')
->label('Active'),
])
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
RelationManagers\ItemsRelationManager::class,
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListMenus::route('/'),
'create' => Pages\CreateMenu::route('/create'),
'edit' => Pages\EditMenu::route('/{record}/edit'),
];
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\MenuResource\Pages;
use App\Filament\Resources\MenuResource;
use Filament\Resources\Pages\CreateRecord;
class CreateMenu extends CreateRecord
{
protected static string $resource = MenuResource::class;
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\MenuResource\Pages;
use App\Filament\Resources\MenuResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditMenu extends EditRecord
{
protected static string $resource = MenuResource::class;
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\MenuResource\Pages;
use App\Filament\Resources\MenuResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListMenus extends ListRecords
{
protected static string $resource = MenuResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -0,0 +1,153 @@
<?php
namespace App\Filament\Resources\MenuResource\RelationManagers;
use App\Models\MenuItem;
use App\Services\MenuService;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Spatie\Permission\Models\Permission;
class ItemsRelationManager extends RelationManager
{
protected static string $relationship = 'allItems';
protected static ?string $title = 'Menu Items';
public function form(Form $form): Form
{
$menuService = app(MenuService::class);
return $form
->schema([
Forms\Components\Section::make('Item Details')
->schema([
Forms\Components\TextInput::make('title')
->required()
->maxLength(255),
Forms\Components\Select::make('type')
->options([
'link' => 'External Link',
'route' => 'Named Route',
'module' => 'Module',
])
->default('link')
->required()
->live(),
Forms\Components\TextInput::make('url')
->label('URL')
->url()
->visible(fn (Forms\Get $get) => $get('type') === 'link')
->required(fn (Forms\Get $get) => $get('type') === 'link'),
Forms\Components\Select::make('route')
->label('Route Name')
->options(fn () => $menuService->getAvailableRoutes())
->searchable()
->visible(fn (Forms\Get $get) => $get('type') === 'route')
->required(fn (Forms\Get $get) => $get('type') === 'route'),
Forms\Components\Select::make('module')
->label('Module')
->options(fn () => $menuService->getAvailableModules())
->searchable()
->visible(fn (Forms\Get $get) => $get('type') === 'module')
->required(fn (Forms\Get $get) => $get('type') === 'module')
->helperText('Users need view permission for this module to see this item'),
])->columns(2),
Forms\Components\Section::make('Permissions & Display')
->schema([
Forms\Components\Select::make('parent_id')
->label('Parent Item')
->options(fn () => MenuItem::where('menu_id', $this->ownerRecord->id)
->whereNull('parent_id')
->pluck('title', 'id'))
->placeholder('None (Top Level)')
->searchable(),
Forms\Components\Select::make('permission')
->label('Required Permission')
->options(fn () => Permission::pluck('name', 'name'))
->searchable()
->placeholder('No specific permission required')
->helperText('If set, user must have this permission to see this item'),
Forms\Components\TextInput::make('icon')
->placeholder('heroicon-o-home')
->helperText('Heroicon name or custom icon class'),
Forms\Components\Select::make('target')
->options([
'_self' => 'Same Window',
'_blank' => 'New Tab',
])
->default('_self'),
Forms\Components\TextInput::make('order')
->numeric()
->default(0)
->helperText('Lower numbers appear first'),
Forms\Components\Toggle::make('is_active')
->label('Active')
->default(true),
])->columns(2),
]);
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('title')
->reorderable('order')
->defaultSort('order')
->columns([
Tables\Columns\TextColumn::make('title')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('parent.title')
->label('Parent')
->placeholder('—')
->badge()
->color('gray'),
Tables\Columns\TextColumn::make('type')
->badge()
->color(fn (string $state) => match ($state) {
'link' => 'info',
'route' => 'success',
'module' => 'warning',
default => 'gray',
}),
Tables\Columns\TextColumn::make('module')
->placeholder('—')
->toggleable(),
Tables\Columns\TextColumn::make('permission')
->placeholder('—')
->toggleable(isToggledHiddenByDefault: true),
Tables\Columns\TextColumn::make('order')
->sortable(),
Tables\Columns\IconColumn::make('is_active')
->label('Active')
->boolean(),
])
->filters([
Tables\Filters\SelectFilter::make('type')
->options([
'link' => 'External Link',
'route' => 'Named Route',
'module' => 'Module',
]),
Tables\Filters\TernaryFilter::make('is_active')
->label('Active'),
])
->headerActions([
Tables\Actions\CreateAction::make(),
])
->actions([
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\PermissionResource\Pages;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Spatie\Permission\Models\Permission;
class PermissionResource extends Resource
{
protected static ?string $model = Permission::class;
protected static ?string $navigationIcon = 'heroicon-o-key';
protected static ?string $navigationGroup = 'User Management';
protected static ?int $navigationSort = 3;
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Section::make('Permission Details')
->schema([
Forms\Components\TextInput::make('name')
->required()
->unique(ignoreRecord: true)
->maxLength(255)
->helperText('Use format: resource.action (e.g., users.create, posts.edit)'),
Forms\Components\Select::make('guard_name')
->options([
'web' => 'Web',
'api' => 'API',
])
->default('web')
->required(),
])->columns(2),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->badge()
->color('info')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('guard_name')
->badge()
->color('gray'),
Tables\Columns\TextColumn::make('roles_count')
->counts('roles')
->label('Roles')
->badge()
->color('success'),
Tables\Columns\TextColumn::make('created_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListPermissions::route('/'),
'create' => Pages\CreatePermission::route('/create'),
'edit' => Pages\EditPermission::route('/{record}/edit'),
];
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\PermissionResource\Pages;
use App\Filament\Resources\PermissionResource;
use Filament\Resources\Pages\CreateRecord;
class CreatePermission extends CreateRecord
{
protected static string $resource = PermissionResource::class;
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\PermissionResource\Pages;
use App\Filament\Resources\PermissionResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditPermission extends EditRecord
{
protected static string $resource = PermissionResource::class;
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\PermissionResource\Pages;
use App\Filament\Resources\PermissionResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListPermissions extends ListRecords
{
protected static string $resource = PermissionResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -0,0 +1,117 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\RoleResource\Pages;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Spatie\Permission\Models\Role;
class RoleResource extends Resource
{
protected static ?string $model = Role::class;
protected static ?string $navigationIcon = 'heroicon-o-shield-check';
protected static ?string $navigationGroup = 'User Management';
protected static ?int $navigationSort = 2;
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Section::make('Role Details')
->schema([
Forms\Components\TextInput::make('name')
->required()
->unique(ignoreRecord: true)
->maxLength(255),
Forms\Components\Select::make('guard_name')
->options([
'web' => 'Web',
'api' => 'API',
])
->default('web')
->required(),
])->columns(2),
Forms\Components\Section::make('Permissions')
->schema([
Forms\Components\CheckboxList::make('permissions')
->relationship('permissions', 'name')
->columns(3)
->helperText('Select permissions for this role'),
]),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->badge()
->color(fn (string $state): string => match ($state) {
'admin' => 'danger',
'editor' => 'warning',
default => 'success',
})
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('guard_name')
->badge()
->color('gray'),
Tables\Columns\TextColumn::make('permissions_count')
->counts('permissions')
->label('Permissions')
->badge()
->color('info'),
Tables\Columns\TextColumn::make('users_count')
->counts('users')
->label('Users')
->badge()
->color('success'),
Tables\Columns\TextColumn::make('created_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make()
->before(function (Role $record) {
if ($record->name === 'admin') {
throw new \Exception('Cannot delete the admin role.');
}
}),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListRoles::route('/'),
'create' => Pages\CreateRole::route('/create'),
'edit' => Pages\EditRole::route('/{record}/edit'),
];
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use Filament\Resources\Pages\CreateRecord;
class CreateRole extends CreateRecord
{
protected static string $resource = RoleResource::class;
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditRole extends EditRecord
{
protected static string $resource = RoleResource::class;
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\RoleResource\Pages;
use App\Filament\Resources\RoleResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListRoles extends ListRecords
{
protected static string $resource = RoleResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -0,0 +1,124 @@
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\UserResource\Pages;
use App\Models\User;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
class UserResource extends Resource
{
protected static ?string $model = User::class;
protected static ?string $navigationIcon = 'heroicon-o-users';
protected static ?string $navigationGroup = 'User Management';
protected static ?int $navigationSort = 1;
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Section::make('User Information')
->schema([
Forms\Components\TextInput::make('name')
->required()
->maxLength(255),
Forms\Components\TextInput::make('email')
->email()
->required()
->unique(ignoreRecord: true)
->maxLength(255),
Forms\Components\DateTimePicker::make('email_verified_at')
->label('Email Verified At'),
])->columns(2),
Forms\Components\Section::make('Password')
->schema([
Forms\Components\TextInput::make('password')
->password()
->dehydrateStateUsing(fn ($state) => Hash::make($state))
->dehydrated(fn ($state) => filled($state))
->required(fn (string $context): bool => $context === 'create')
->maxLength(255)
->confirmed(),
Forms\Components\TextInput::make('password_confirmation')
->password()
->maxLength(255)
->dehydrated(false),
])->columns(2),
Forms\Components\Section::make('Roles')
->schema([
Forms\Components\CheckboxList::make('roles')
->relationship('roles', 'name')
->columns(3)
->helperText('Assign roles to this user'),
]),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('email')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('roles.name')
->badge()
->color('success')
->separator(','),
Tables\Columns\IconColumn::make('email_verified_at')
->label('Verified')
->boolean()
->trueIcon('heroicon-o-check-circle')
->falseIcon('heroicon-o-x-circle'),
Tables\Columns\TextColumn::make('created_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
Tables\Filters\SelectFilter::make('roles')
->relationship('roles', 'name')
->multiple()
->preload(),
])
->actions([
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListUsers::route('/'),
'create' => Pages\CreateUser::route('/create'),
'edit' => Pages\EditUser::route('/{record}/edit'),
];
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource;
use Filament\Actions;
use Filament\Resources\Pages\CreateRecord;
class CreateUser extends CreateRecord
{
protected static string $resource = UserResource::class;
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;
class EditUser extends EditRecord
{
protected static string $resource = UserResource::class;
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make(),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
class ListUsers extends ListRecords
{
protected static string $resource = UserResource::class;
protected function getHeaderActions(): array
{
return [
Actions\CreateAction::make(),
];
}
}

View File

@@ -0,0 +1,88 @@
<?php
namespace App\Helpers;
class ViteHelper
{
/**
* Check if the Vite manifest exists (assets have been built).
*/
public static function manifestExists(): bool
{
return file_exists(public_path('build/manifest.json'));
}
/**
* Get fallback CSS for when Vite assets are not built.
* This provides basic styling so the app remains usable.
*/
public static function fallbackStyles(): string
{
return <<<'CSS'
<style>
/* Fallback styles when Vite assets are not built */
*, *::before, *::after { box-sizing: border-box; }
body {
font-family: ui-sans-serif, system-ui, sans-serif;
margin: 0;
background: #f3f4f6;
color: #111827;
}
.dark body { background: #111827; color: #f9fafb; }
.min-h-screen { min-height: 100vh; }
.bg-gray-100 { background: #f3f4f6; }
.bg-white { background: #fff; }
.shadow { box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.max-w-7xl { max-width: 80rem; margin: 0 auto; }
.px-4 { padding-left: 1rem; padding-right: 1rem; }
.py-6 { padding-top: 1.5rem; padding-bottom: 1.5rem; }
.font-semibold { font-weight: 600; }
.text-xl { font-size: 1.25rem; }
.text-gray-800 { color: #1f2937; }
a { color: #3b82f6; text-decoration: none; }
a:hover { text-decoration: underline; }
.hidden { display: none; }
.flex { display: flex; }
.items-center { align-items: center; }
.justify-between { justify-content: space-between; }
.space-x-4 > * + * { margin-left: 1rem; }
nav { background: #fff; border-bottom: 1px solid #e5e7eb; padding: 1rem; }
.container { max-width: 80rem; margin: 0 auto; padding: 0 1rem; }
button, .btn {
padding: 0.5rem 1rem;
background: #3b82f6;
color: white;
border: none;
border-radius: 0.375rem;
cursor: pointer;
}
button:hover, .btn:hover { background: #2563eb; }
input, select, textarea {
border: 1px solid #d1d5db;
border-radius: 0.375rem;
padding: 0.5rem 0.75rem;
width: 100%;
}
.alert { padding: 1rem; border-radius: 0.375rem; margin-bottom: 1rem; }
.alert-warning { background: #fef3c7; border: 1px solid #f59e0b; color: #92400e; }
</style>
CSS;
}
/**
* Get a warning banner HTML for development.
*/
public static function devWarningBanner(): string
{
if (app()->environment('production')) {
return '';
}
return <<<'HTML'
<div class="alert alert-warning" style="margin:1rem;padding:1rem;background:#fef3c7;border:1px solid #f59e0b;border-radius:0.5rem;color:#92400e;">
<strong>⚠️ Development Notice:</strong> Vite assets are not built.
Run <code style="background:#fde68a;padding:0.125rem 0.25rem;border-radius:0.25rem;">docker-compose run --rm node npm run build</code> to build assets.
</div>
HTML;
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*/
public function create(): View
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*/
public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(route('dashboard', absolute: false));
}
/**
* Destroy an authenticated session.
*/
public function destroy(Request $request): RedirectResponse
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class ConfirmablePasswordController extends Controller
{
/**
* Show the confirm password view.
*/
public function show(): View
{
return view('auth.confirm-password');
}
/**
* Confirm the user's password.
*/
public function store(Request $request): RedirectResponse
{
if (! Auth::guard('web')->validate([
'email' => $request->user()->email,
'password' => $request->password,
])) {
throw ValidationException::withMessages([
'password' => __('auth.password'),
]);
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended(route('dashboard', absolute: false));
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class EmailVerificationNotificationController extends Controller
{
/**
* Send a new email verification notification.
*/
public function store(Request $request): RedirectResponse
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(route('dashboard', absolute: false));
}
$request->user()->sendEmailVerificationNotification();
return back()->with('status', 'verification-link-sent');
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class EmailVerificationPromptController extends Controller
{
/**
* Display the email verification prompt.
*/
public function __invoke(Request $request): RedirectResponse|View
{
return $request->user()->hasVerifiedEmail()
? redirect()->intended(route('dashboard', absolute: false))
: view('auth.verify-email');
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
class NewPasswordController extends Controller
{
/**
* Display the password reset view.
*/
public function create(Request $request): View
{
return view('auth.reset-password', ['request' => $request]);
}
/**
* Handle an incoming new password request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'token' => ['required'],
'email' => ['required', 'email'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function (User $user) use ($request) {
$user->forceFill([
'password' => Hash::make($request->password),
'remember_token' => Str::random(60),
])->save();
event(new PasswordReset($user));
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $status == Password::PASSWORD_RESET
? redirect()->route('login')->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
class PasswordController extends Controller
{
/**
* Update the user's password.
*/
public function update(Request $request): RedirectResponse
{
$validated = $request->validateWithBag('updatePassword', [
'current_password' => ['required', 'current_password'],
'password' => ['required', Password::defaults(), 'confirmed'],
]);
$request->user()->update([
'password' => Hash::make($validated['password']),
]);
return back()->with('status', 'password-updated');
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\View\View;
class PasswordResetLinkController extends Controller
{
/**
* Display the password reset link request view.
*/
public function create(): View
{
return view('auth.forgot-password');
}
/**
* Handle an incoming password reset link request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'email' => ['required', 'email'],
]);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$status = Password::sendResetLink(
$request->only('email')
);
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*/
public function create(): View
{
return view('auth.register');
}
/**
* Handle an incoming registration request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(route('dashboard', absolute: false));
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\RedirectResponse;
class VerifyEmailController extends Controller
{
/**
* Mark the authenticated user's email address as verified.
*/
public function __invoke(EmailVerificationRequest $request): RedirectResponse
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}

View File

@@ -0,0 +1,60 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ProfileUpdateRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;
class ProfileController extends Controller
{
/**
* Display the user's profile form.
*/
public function edit(Request $request): View
{
return view('profile.edit', [
'user' => $request->user(),
]);
}
/**
* Update the user's profile information.
*/
public function update(ProfileUpdateRequest $request): RedirectResponse
{
$request->user()->fill($request->validated());
if ($request->user()->isDirty('email')) {
$request->user()->email_verified_at = null;
}
$request->user()->save();
return Redirect::route('profile.edit')->with('status', 'profile-updated');
}
/**
* Delete the user's account.
*/
public function destroy(Request $request): RedirectResponse
{
$request->validateWithBag('userDeletion', [
'password' => ['required', 'current_password'],
]);
$user = $request->user();
Auth::logout();
$user->delete();
$request->session()->invalidate();
$request->session()->regenerateToken();
return Redirect::to('/');
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Http\Middleware;
use App\Models\Setting;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class CheckRegistrationEnabled
{
/**
* Handle an incoming request.
* Block registration routes if registration is disabled in settings.
*/
public function handle(Request $request, Closure $next): Response
{
$registrationEnabled = Setting::get('enable_registration', false);
if (!$registrationEnabled) {
abort(403, 'User registration is currently disabled. Please contact an administrator.');
}
return $next($request);
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'email' => ['required', 'string', 'email'],
'password' => ['required', 'string'],
];
}
/**
* Attempt to authenticate the request's credentials.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function authenticate(): void
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function ensureIsNotRateLimited(): void
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*/
public function throttleKey(): string
{
return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip());
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests;
use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class ProfileUpdateRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'lowercase',
'email',
'max:255',
Rule::unique(User::class)->ignore($this->user()->id),
],
];
}
}

111
src/app/Models/Audit.php Normal file
View File

@@ -0,0 +1,111 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class Audit extends Model
{
protected $table = 'audits';
protected $guarded = [];
protected $casts = [
'old_values' => 'array',
'new_values' => 'array',
];
/**
* Get the user that performed the action.
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* Get the auditable model.
*/
public function auditable(): MorphTo
{
return $this->morphTo();
}
/**
* Get the event badge color.
*/
public function getEventColorAttribute(): string
{
return match ($this->event) {
'created' => 'success',
'updated' => 'warning',
'deleted' => 'danger',
'restored' => 'info',
default => 'gray',
};
}
/**
* Get a human-readable model name.
*/
public function getModelNameAttribute(): string
{
$class = class_basename($this->auditable_type);
return preg_replace('/(?<!^)[A-Z]/', ' $0', $class);
}
/**
* Get formatted changes for display.
*/
public function getFormattedChangesAttribute(): array
{
$changes = [];
$oldValues = $this->old_values ?? [];
$newValues = $this->new_values ?? [];
$allKeys = array_unique(array_merge(array_keys($oldValues), array_keys($newValues)));
foreach ($allKeys as $key) {
$old = $oldValues[$key] ?? null;
$new = $newValues[$key] ?? null;
if ($old !== $new) {
$changes[] = [
'field' => $key,
'old' => $this->formatValue($old),
'new' => $this->formatValue($new),
];
}
}
return $changes;
}
/**
* Format a value for display.
*/
protected function formatValue($value): string
{
if (is_null($value)) {
return '(empty)';
}
if (is_bool($value)) {
return $value ? 'Yes' : 'No';
}
if (is_array($value)) {
return json_encode($value);
}
$stringValue = (string) $value;
if (strlen($stringValue) > 100) {
return substr($stringValue, 0, 100) . '...';
}
return $stringValue;
}
}

40
src/app/Models/Menu.php Normal file
View File

@@ -0,0 +1,40 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Menu extends Model
{
protected $fillable = [
'name',
'slug',
'location',
'is_active',
];
protected $casts = [
'is_active' => 'boolean',
];
public function items(): HasMany
{
return $this->hasMany(MenuItem::class)->whereNull('parent_id')->orderBy('order');
}
public function allItems(): HasMany
{
return $this->hasMany(MenuItem::class)->orderBy('order');
}
public static function findBySlug(string $slug): ?self
{
return static::where('slug', $slug)->where('is_active', true)->first();
}
public static function findByLocation(string $location): ?self
{
return static::where('location', $location)->where('is_active', true)->first();
}
}

View File

@@ -0,0 +1,90 @@
<?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\Auth;
class MenuItem extends Model
{
protected $fillable = [
'menu_id',
'parent_id',
'title',
'type',
'url',
'route',
'route_params',
'module',
'permission',
'icon',
'target',
'order',
'is_active',
];
protected $casts = [
'route_params' => 'array',
'is_active' => 'boolean',
'order' => 'integer',
];
public function menu(): BelongsTo
{
return $this->belongsTo(Menu::class);
}
public function parent(): BelongsTo
{
return $this->belongsTo(MenuItem::class, 'parent_id');
}
public function children(): HasMany
{
return $this->hasMany(MenuItem::class, 'parent_id')->orderBy('order');
}
public function getUrlAttribute(): ?string
{
return match ($this->type) {
'link' => $this->attributes['url'],
'route' => $this->route ? route($this->route, $this->route_params ?? []) : null,
'module' => $this->module ? route("{$this->module}.index") : null,
default => null,
};
}
public function isVisibleToUser(?User $user = null): bool
{
if (!$this->is_active) {
return false;
}
$user = $user ?? Auth::user();
if (!$user) {
return !$this->permission && !$this->module;
}
if ($user->hasRole('admin')) {
return true;
}
if ($this->permission) {
return $user->can($this->permission);
}
if ($this->module) {
return $user->can("{$this->module}.view");
}
return true;
}
public function getVisibleChildren(?User $user = null): \Illuminate\Support\Collection
{
return $this->children->filter(fn (MenuItem $item) => $item->isVisibleToUser($user));
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $fillable = ['key', 'value', 'type'];
public static function get(string $key, $default = null)
{
$setting = static::where('key', $key)->first();
if (!$setting) {
return $default;
}
return match ($setting->type) {
'boolean' => filter_var($setting->value, FILTER_VALIDATE_BOOLEAN),
'integer' => (int) $setting->value,
'array', 'json' => json_decode($setting->value, true),
default => $setting->value,
};
}
public static function set(string $key, $value, string $type = 'string'): void
{
if (in_array($type, ['array', 'json'])) {
$value = json_encode($value);
}
static::updateOrCreate(
['key' => $key],
['value' => $value, 'type' => $type]
);
}
}

57
src/app/Models/User.php Normal file
View File

@@ -0,0 +1,57 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements FilamentUser
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable, HasRoles, HasApiTokens;
public function canAccessPanel(Panel $panel): bool
{
return $this->hasRole('admin');
}
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}

131
src/app/Modules/README.md Normal file
View File

@@ -0,0 +1,131 @@
# Module System
> **🤖 AI Agents**: For EXACT file templates, see [CLAUDE.md](../../../CLAUDE.md)
This Laravel application uses a modular architecture to organize features into self-contained modules.
## Creating a New Module
```bash
# Basic module (no model)
php artisan make:module ProductCatalog
# With a model + Filament resource
php artisan make:module ProductCatalog --model=Product
# With API routes
php artisan make:module ProductCatalog --model=Product --api
# Without Filament admin
php artisan make:module ProductCatalog --model=Product --no-filament
```
## What Gets Created
### Basic module (`make:module Name`):
```
app/Modules/Name/
├── Config/name.php # Module config
├── Database/Migrations/ # Module migrations
├── Database/Seeders/
├── Filament/Resources/ # Admin resources
├── Http/Controllers/NameController.php
├── Http/Middleware/
├── Http/Requests/
├── Models/
├── Policies/
├── Services/
├── Routes/web.php # Frontend routes
├── Resources/views/index.blade.php
├── Permissions.php # Module permissions
└── NameServiceProvider.php # Auto-registered
```
### With `--model=Product`:
Adds:
- `Models/Product.php` (with auditing)
- `Database/Migrations/create_products_table.php`
- `Filament/Resources/ProductResource.php` (full CRUD)
### With `--api`:
Adds:
- `Routes/api.php` (Sanctum-protected)
## Module Features
**ServiceProvider** - Auto-registered, loads routes/views/migrations
**Config** - Module-specific settings with audit configuration
**Permissions** - Pre-defined CRUD permissions
**Filament Admin** - Full CRUD resource with navigation group
**Auditing** - Track all changes via ModuleAuditable trait
**Tests** - Feature tests with permission checks
## Example Usage
```bash
# Create a Stock Management module with Product model
php artisan make:module StockManagement --model=Product --api
# Run migrations
php artisan migrate
# Seed permissions
php artisan db:seed --class=RolePermissionSeeder
# Clear caches
php artisan optimize:clear
```
**Access:**
- Frontend: `http://localhost:8080/stock-management`
- Admin: `http://localhost:8080/admin` → Stock Management section
- API: `http://localhost:8080/api/stock-management`
## Permissions
Each module creates these permissions in `Permissions.php`:
```php
return [
'stock_management.view' => 'View Stock Management',
'stock_management.create' => 'Create Stock Management records',
'stock_management.edit' => 'Edit Stock Management records',
'stock_management.delete' => 'Delete Stock Management records',
];
```
**Permissions are auto-loaded!** When you run `php artisan db:seed --class=RolePermissionSeeder`,
it scans all `app/Modules/*/Permissions.php` files and registers them automatically.
Use in Blade:
```blade
@can('stock_management.view')
<a href="{{ route('stock-management.index') }}">Stock</a>
@endcan
```
Use in Controller:
```php
$this->authorize('stock_management.view');
```
## Audit Configuration
Edit `Config/module_name.php`:
```php
'audit' => [
'enabled' => true,
'strategy' => 'all', // 'all', 'include', 'exclude', 'none'
'include' => [], // Fields to audit (if strategy='include')
'exclude' => ['password'], // Fields to exclude
],
```
## Best Practices
1. **Keep modules independent** - Avoid tight coupling between modules
2. **Use Services** - Put business logic in `Services/`, not controllers
3. **Define clear permissions** - One permission per action
4. **Test your modules** - Run `php artisan test` after creating
5. **Use Filament** - Leverage admin panel for quick CRUD

View File

@@ -0,0 +1,48 @@
<?php
namespace App\Providers;
use App\Models\Setting;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
View::composer('*', function ($view) {
try {
$view->with('siteSettings', [
'name' => Setting::get('site_name', config('app.name', 'Laravel')),
'logo' => Setting::get('site_logo'),
'primary_color' => Setting::get('primary_color', '#3b82f6'),
'secondary_color' => Setting::get('secondary_color', '#8b5cf6'),
'accent_color' => Setting::get('accent_color', '#10b981'),
'description' => Setting::get('site_description'),
'enable_registration' => Setting::get('enable_registration', false),
]);
} catch (\Exception $e) {
$view->with('siteSettings', [
'name' => config('app.name', 'Laravel'),
'logo' => null,
'primary_color' => '#3b82f6',
'secondary_color' => '#8b5cf6',
'accent_color' => '#10b981',
'description' => null,
'enable_registration' => false,
]);
}
});
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace App\Providers\Filament;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use Filament\Pages;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\Support\Colors\Color;
use Filament\Widgets;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
class AdminPanelProvider extends PanelProvider
{
public function panel(Panel $panel): Panel
{
return $panel
->default()
->id('admin')
->path('admin')
->login()
->colors([
'primary' => Color::Amber,
])
->discoverResources(in: app_path('Filament/Resources'), for: 'App\\Filament\\Resources')
->discoverPages(in: app_path('Filament/Pages'), for: 'App\\Filament\\Pages')
->pages([
Pages\Dashboard::class,
])
->discoverWidgets(in: app_path('Filament/Widgets'), for: 'App\\Filament\\Widgets')
->widgets([
Widgets\AccountWidget::class,
Widgets\FilamentInfoWidget::class,
])
->middleware([
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
AuthenticateSession::class,
ShareErrorsFromSession::class,
VerifyCsrfToken::class,
SubstituteBindings::class,
DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class,
])
->authMiddleware([
Authenticate::class,
]);
}
}

View File

@@ -0,0 +1,117 @@
<?php
namespace App\Services;
use App\Models\Menu;
use App\Models\MenuItem;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
class MenuService
{
public function getMenu(string $slugOrLocation, ?User $user = null): ?array
{
$menu = Menu::findBySlug($slugOrLocation) ?? Menu::findByLocation($slugOrLocation);
if (!$menu) {
return null;
}
return $this->buildMenuTree($menu, $user);
}
public function buildMenuTree(Menu $menu, ?User $user = null): array
{
$user = $user ?? Auth::user();
$items = $menu->items()
->with(['children' => fn ($q) => $q->orderBy('order')])
->where('is_active', true)
->get();
return $this->filterAndMapItems($items, $user);
}
protected function filterAndMapItems(Collection $items, ?User $user): array
{
return $items
->filter(fn (MenuItem $item) => $item->isVisibleToUser($user))
->map(fn (MenuItem $item) => $this->mapItem($item, $user))
->values()
->toArray();
}
protected function mapItem(MenuItem $item, ?User $user): array
{
$children = $item->children->count() > 0
? $this->filterAndMapItems($item->children, $user)
: [];
return [
'id' => $item->id,
'title' => $item->title,
'url' => $item->url,
'icon' => $item->icon,
'target' => $item->target,
'is_active' => $this->isActiveUrl($item->url),
'children' => $children,
'has_children' => count($children) > 0,
];
}
protected function isActiveUrl(?string $url): bool
{
if (!$url) {
return false;
}
$currentUrl = request()->url();
$currentPath = request()->path();
if ($url === $currentUrl) {
return true;
}
$urlPath = parse_url($url, PHP_URL_PATH) ?? '';
return $urlPath && str_starts_with('/' . ltrim($currentPath, '/'), $urlPath);
}
public function getAvailableModules(): array
{
$modules = [];
$modulesPath = app_path('Modules');
if (!is_dir($modulesPath)) {
return $modules;
}
foreach (scandir($modulesPath) as $module) {
if ($module === '.' || $module === '..' || !is_dir($modulesPath . '/' . $module)) {
continue;
}
$slug = strtolower(preg_replace('/(?<!^)[A-Z]/', '-$0', $module));
$modules[$slug] = $module;
}
return $modules;
}
public function getAvailableRoutes(): array
{
$routes = [];
foreach (app('router')->getRoutes() as $route) {
$name = $route->getName();
if ($name && !str_starts_with($name, 'filament.') && !str_starts_with($name, 'livewire.')) {
$routes[$name] = $name;
}
}
ksort($routes);
return $routes;
}
}

View File

@@ -0,0 +1,248 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
class ModuleDiscoveryService
{
public function discoverModules(): array
{
$modulesPath = app_path('Modules');
if (!File::exists($modulesPath)) {
return [];
}
$modules = [];
$directories = File::directories($modulesPath);
foreach ($directories as $directory) {
$moduleName = basename($directory);
// Skip non-module directories (like README files)
if (!File::exists("{$directory}/{$moduleName}ServiceProvider.php")) {
continue;
}
$modules[] = $this->getModuleInfo($moduleName, $directory);
}
return $modules;
}
protected function getModuleInfo(string $name, string $path): array
{
$kebabName = Str::kebab($name);
$snakeName = Str::snake($name);
return [
'name' => $name,
'slug' => $kebabName,
'path' => $path,
'config' => $this->getConfig($path, $snakeName),
'models' => $this->getModels($path),
'views' => $this->getViews($path),
'routes' => $this->getRoutes($path, $kebabName),
'migrations' => $this->getMigrations($path),
'filament_resources' => $this->getFilamentResources($path),
'permissions' => $this->getPermissions($path),
'has_api' => File::exists("{$path}/Routes/api.php"),
];
}
protected function getConfig(string $path, string $snakeName): array
{
$configPath = "{$path}/Config/{$snakeName}.php";
if (File::exists($configPath)) {
return require $configPath;
}
return [];
}
protected function getModels(string $path): array
{
$modelsPath = "{$path}/Models";
if (!File::exists($modelsPath)) {
return [];
}
$models = [];
$files = File::files($modelsPath);
foreach ($files as $file) {
if ($file->getExtension() === 'php' && $file->getFilename() !== '.gitkeep') {
$modelName = $file->getFilenameWithoutExtension();
$models[] = [
'name' => $modelName,
'file' => $file->getFilename(),
'path' => $file->getPathname(),
];
}
}
return $models;
}
protected function getViews(string $path): array
{
$viewsPath = "{$path}/Resources/views";
if (!File::exists($viewsPath)) {
return [];
}
return $this->scanViewsRecursive($viewsPath, '');
}
protected function scanViewsRecursive(string $basePath, string $prefix): array
{
$views = [];
$items = File::files($basePath);
foreach ($items as $file) {
if ($file->getExtension() === 'php' && Str::endsWith($file->getFilename(), '.blade.php')) {
$viewName = Str::replaceLast('.blade.php', '', $file->getFilename());
$fullName = $prefix ? "{$prefix}.{$viewName}" : $viewName;
$views[] = [
'name' => $fullName,
'file' => $file->getFilename(),
'path' => $file->getPathname(),
];
}
}
// Scan subdirectories
$directories = File::directories($basePath);
foreach ($directories as $dir) {
$dirName = basename($dir);
$subPrefix = $prefix ? "{$prefix}.{$dirName}" : $dirName;
$views = array_merge($views, $this->scanViewsRecursive($dir, $subPrefix));
}
return $views;
}
protected function getRoutes(string $path, string $kebabName): array
{
$routes = [];
// Get web routes
$webRoutesPath = "{$path}/Routes/web.php";
if (File::exists($webRoutesPath)) {
$routes['web'] = $this->parseRouteFile($webRoutesPath, $kebabName);
}
// Get API routes
$apiRoutesPath = "{$path}/Routes/api.php";
if (File::exists($apiRoutesPath)) {
$routes['api'] = $this->parseRouteFile($apiRoutesPath, "api/{$kebabName}");
}
return $routes;
}
protected function parseRouteFile(string $path, string $prefix): array
{
$content = File::get($path);
$routes = [];
// Parse Route::get, Route::post, etc.
preg_match_all(
"/Route::(get|post|put|patch|delete|any)\s*\(\s*['\"]([^'\"]*)['\"].*?->name\s*\(\s*['\"]([^'\"]*)['\"]|Route::(get|post|put|patch|delete|any)\s*\(\s*['\"]([^'\"]*)['\"].*?\[.*?::class,\s*['\"](\w+)['\"]\]/",
$content,
$matches,
PREG_SET_ORDER
);
foreach ($matches as $match) {
$method = strtoupper($match[1] ?: $match[4]);
$uri = $match[2] ?: $match[5];
$fullUri = $uri === '/' ? "/{$prefix}" : "/{$prefix}{$uri}";
$routes[] = [
'method' => $method,
'uri' => $fullUri,
'name' => $match[3] ?? null,
];
}
return $routes;
}
protected function getMigrations(string $path): array
{
$migrationsPath = "{$path}/Database/Migrations";
if (!File::exists($migrationsPath)) {
return [];
}
$migrations = [];
$files = File::files($migrationsPath);
foreach ($files as $file) {
if ($file->getExtension() === 'php') {
$migrations[] = [
'name' => $file->getFilename(),
'path' => $file->getPathname(),
];
}
}
return $migrations;
}
protected function getFilamentResources(string $path): array
{
$resourcesPath = "{$path}/Filament/Resources";
if (!File::exists($resourcesPath)) {
return [];
}
$resources = [];
$files = File::files($resourcesPath);
foreach ($files as $file) {
if ($file->getExtension() === 'php' && Str::endsWith($file->getFilename(), 'Resource.php')) {
$resourceName = Str::replaceLast('Resource.php', '', $file->getFilename());
$resources[] = [
'name' => $resourceName,
'file' => $file->getFilename(),
'path' => $file->getPathname(),
];
}
}
return $resources;
}
protected function getPermissions(string $path): array
{
$permissionsPath = "{$path}/Permissions.php";
if (File::exists($permissionsPath)) {
return require $permissionsPath;
}
return [];
}
public function getModuleSummary(): array
{
$modules = $this->discoverModules();
return [
'total' => count($modules),
'with_models' => count(array_filter($modules, fn($m) => !empty($m['models']))),
'with_filament' => count(array_filter($modules, fn($m) => !empty($m['filament_resources']))),
'with_api' => count(array_filter($modules, fn($m) => $m['has_api'])),
];
}
}

View File

@@ -0,0 +1,492 @@
<?php
namespace App\Services;
use CzProject\GitPhp\Git;
use CzProject\GitPhp\GitRepository;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
class ModuleGeneratorService
{
protected string $studlyName;
protected string $kebabName;
protected string $snakeName;
protected string $modulePath;
protected array $logs = [];
protected ?GitRepository $repo = null;
public function generate(string $name, array $options = []): array
{
$this->studlyName = Str::studly($name);
$this->kebabName = Str::kebab($name);
$this->snakeName = Str::snake($name);
$this->modulePath = app_path("Modules/{$this->studlyName}");
$options = array_merge([
'description' => '',
'create_git_branch' => true,
'include_api' => false,
], $options);
// Check if module already exists
if (File::exists($this->modulePath)) {
return [
'success' => false,
'message' => "Module {$this->studlyName} already exists!",
'logs' => $this->logs,
];
}
// Handle Git branching
$branchName = null;
if ($options['create_git_branch']) {
$gitResult = $this->createGitBranch();
if (!$gitResult['success']) {
return $gitResult;
}
$branchName = $gitResult['branch'];
}
// Generate module skeleton
$this->createDirectoryStructure();
$this->createServiceProvider($options['description']);
$this->createConfig($options['description']);
$this->createPermissions();
$this->createController();
$this->createRoutes($options['include_api']);
$this->createViews();
$this->createReadme($options['description']);
$this->registerServiceProvider();
// Git commit
if ($options['create_git_branch'] && $this->repo) {
$this->commitChanges();
}
return [
'success' => true,
'message' => "Module {$this->studlyName} created successfully!",
'module_name' => $this->studlyName,
'module_path' => $this->modulePath,
'branch' => $branchName,
'logs' => $this->logs,
'next_steps' => $this->getNextSteps($branchName),
];
}
protected function createGitBranch(): array
{
try {
$git = new Git();
$repoPath = base_path();
// Check if we're in a git repository
if (!File::exists($repoPath . '/.git')) {
$this->log('⚠ No Git repository found, skipping branch creation');
return ['success' => true, 'branch' => null];
}
$this->repo = $git->open($repoPath);
// Check for uncommitted changes
if ($this->repo->hasChanges()) {
return [
'success' => false,
'message' => 'Git working directory has uncommitted changes. Please commit or stash them first.',
'logs' => $this->logs,
];
}
$branchName = "module/{$this->kebabName}";
// Create and checkout new branch
$this->repo->createBranch($branchName, true);
$this->log("✓ Created and checked out branch: {$branchName}");
return ['success' => true, 'branch' => $branchName];
} catch (\Exception $e) {
return [
'success' => false,
'message' => 'Git error: ' . $e->getMessage(),
'logs' => $this->logs,
];
}
}
protected function commitChanges(): void
{
try {
$this->repo->addAllChanges();
$this->repo->commit("feat: Add {$this->studlyName} module skeleton");
$this->log("✓ Committed changes to Git");
} catch (\Exception $e) {
$this->log("⚠ Git commit failed: " . $e->getMessage());
}
}
protected function createDirectoryStructure(): void
{
$directories = [
'',
'/Config',
'/Database/Migrations',
'/Database/Seeders',
'/Filament/Resources',
'/Http/Controllers',
'/Http/Middleware',
'/Http/Requests',
'/Models',
'/Policies',
'/Services',
'/Routes',
'/Resources/views',
];
foreach ($directories as $dir) {
File::makeDirectory("{$this->modulePath}{$dir}", 0755, true);
}
// Create .gitkeep files in empty directories
$emptyDirs = [
'/Database/Migrations',
'/Database/Seeders',
'/Filament/Resources',
'/Http/Middleware',
'/Http/Requests',
'/Models',
'/Policies',
'/Services',
];
foreach ($emptyDirs as $dir) {
File::put("{$this->modulePath}{$dir}/.gitkeep", '');
}
$this->log("✓ Created directory structure");
}
protected function createServiceProvider(string $description): void
{
$stub = <<<PHP
<?php
namespace App\Modules\\{$this->studlyName};
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Route;
class {$this->studlyName}ServiceProvider extends ServiceProvider
{
public function register(): void
{
\$this->mergeConfigFrom(
__DIR__ . '/Config/{$this->snakeName}.php',
'{$this->snakeName}'
);
}
public function boot(): void
{
\$this->loadMigrationsFrom(__DIR__ . '/Database/Migrations');
\$this->loadViewsFrom(__DIR__ . '/Resources/views', '{$this->kebabName}');
\$this->registerRoutes();
\$this->registerPermissions();
}
protected function registerRoutes(): void
{
Route::middleware(['web', 'auth'])
->prefix('{$this->kebabName}')
->name('{$this->kebabName}.')
->group(__DIR__ . '/Routes/web.php');
if (file_exists(__DIR__ . '/Routes/api.php')) {
Route::middleware(['api', 'auth:sanctum'])
->prefix('api/{$this->kebabName}')
->name('api.{$this->kebabName}.')
->group(__DIR__ . '/Routes/api.php');
}
}
protected function registerPermissions(): void
{
// Permissions are registered via RolePermissionSeeder
// See: Permissions.php in this module
}
}
PHP;
File::put("{$this->modulePath}/{$this->studlyName}ServiceProvider.php", $stub);
$this->log("✓ Created ServiceProvider");
}
protected function createConfig(string $description): void
{
$stub = <<<PHP
<?php
return [
'name' => '{$this->studlyName}',
'slug' => '{$this->kebabName}',
'description' => '{$description}',
'version' => '1.0.0',
'audit' => [
'enabled' => true,
'strategy' => 'all', // 'all', 'include', 'exclude', 'none'
'include' => [],
'exclude' => [],
],
];
PHP;
File::put("{$this->modulePath}/Config/{$this->snakeName}.php", $stub);
$this->log("✓ Created Config");
}
protected function createPermissions(): void
{
$stub = <<<PHP
<?php
return [
'{$this->snakeName}.view' => 'View {$this->studlyName}',
'{$this->snakeName}.create' => 'Create {$this->studlyName} records',
'{$this->snakeName}.edit' => 'Edit {$this->studlyName} records',
'{$this->snakeName}.delete' => 'Delete {$this->studlyName} records',
];
PHP;
File::put("{$this->modulePath}/Permissions.php", $stub);
$this->log("✓ Created Permissions");
}
protected function createController(): void
{
$stub = <<<PHP
<?php
namespace App\Modules\\{$this->studlyName}\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class {$this->studlyName}Controller extends Controller
{
public function index()
{
\$this->authorize('{$this->snakeName}.view');
return view('{$this->kebabName}::index');
}
}
PHP;
File::put("{$this->modulePath}/Http/Controllers/{$this->studlyName}Controller.php", $stub);
$this->log("✓ Created Controller");
}
protected function createRoutes(bool $includeApi): void
{
// Web routes
$webStub = <<<PHP
<?php
use App\Modules\\{$this->studlyName}\Http\Controllers\\{$this->studlyName}Controller;
use Illuminate\Support\Facades\Route;
Route::get('/', [{$this->studlyName}Controller::class, 'index'])->name('index');
// Add more routes here:
// Route::get('/create', [{$this->studlyName}Controller::class, 'create'])->name('create');
// Route::post('/', [{$this->studlyName}Controller::class, 'store'])->name('store');
// Route::get('/{id}', [{$this->studlyName}Controller::class, 'show'])->name('show');
// Route::get('/{id}/edit', [{$this->studlyName}Controller::class, 'edit'])->name('edit');
// Route::put('/{id}', [{$this->studlyName}Controller::class, 'update'])->name('update');
// Route::delete('/{id}', [{$this->studlyName}Controller::class, 'destroy'])->name('destroy');
PHP;
File::put("{$this->modulePath}/Routes/web.php", $webStub);
// API routes (if requested)
if ($includeApi) {
$apiStub = <<<PHP
<?php
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->group(function () {
// API routes here
// Route::get('/', fn() => response()->json(['message' => '{$this->studlyName} API']));
});
PHP;
File::put("{$this->modulePath}/Routes/api.php", $apiStub);
$this->log("✓ Created Routes (web + api)");
} else {
$this->log("✓ Created Routes (web)");
}
}
protected function createViews(): void
{
$stub = <<<BLADE
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
{{ __('{$this->studlyName}') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 text-gray-900 dark:text-gray-100">
<h3 class="text-lg font-medium mb-4">{{ __('{$this->studlyName} Module') }}</h3>
<p class="text-gray-600 dark:text-gray-400">
This is your new module. Start building by adding models, controllers, and views.
</p>
<div class="mt-6 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg">
<h4 class="font-medium mb-2">Quick Start:</h4>
<ul class="list-disc list-inside text-sm space-y-1">
<li>Add models in <code>app/Modules/{$this->studlyName}/Models/</code></li>
<li>Add migrations in <code>app/Modules/{$this->studlyName}/Database/Migrations/</code></li>
<li>Add Filament resources in <code>app/Modules/{$this->studlyName}/Filament/Resources/</code></li>
<li>Extend routes in <code>app/Modules/{$this->studlyName}/Routes/web.php</code></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</x-app-layout>
BLADE;
File::put("{$this->modulePath}/Resources/views/index.blade.php", $stub);
$this->log("✓ Created Views");
}
protected function createReadme(string $description): void
{
$stub = <<<MD
# {$this->studlyName} Module
{$description}
## Structure
```
{$this->studlyName}/
├── Config/{$this->snakeName}.php # Module configuration
├── Database/
├── Migrations/ # Database migrations
└── Seeders/ # Database seeders
├── Filament/Resources/ # Admin panel resources
├── Http/
├── Controllers/ # HTTP controllers
├── Middleware/ # Module middleware
└── Requests/ # Form requests
├── Models/ # Eloquent models
├── Policies/ # Authorization policies
├── Services/ # Business logic services
├── Routes/
├── web.php # Web routes
└── api.php # API routes (if enabled)
├── Resources/views/ # Blade templates
├── Permissions.php # Module permissions
├── {$this->studlyName}ServiceProvider.php
└── README.md
```
## Permissions
| Permission | Description |
|------------|-------------|
| `{$this->snakeName}.view` | View {$this->studlyName} |
| `{$this->snakeName}.create` | Create records |
| `{$this->snakeName}.edit` | Edit records |
| `{$this->snakeName}.delete` | Delete records |
## Routes
| Method | URI | Name | Description |
|--------|-----|------|-------------|
| GET | `/{$this->kebabName}` | `{$this->kebabName}.index` | Module index |
## Getting Started
1. **Add a Model:**
```bash
# Create model manually or use artisan
php artisan make:model Modules/{$this->studlyName}/Models/YourModel -m
```
2. **Run Migrations:**
```bash
php artisan migrate
```
3. **Seed Permissions:**
```bash
php artisan db:seed --class=RolePermissionSeeder
```
4. **Add Filament Resource:**
Create resources in `Filament/Resources/` following the Filament documentation.
## Configuration
Edit `Config/{$this->snakeName}.php` to customize module settings including audit behavior.
MD;
File::put("{$this->modulePath}/README.md", $stub);
$this->log("✓ Created README.md");
}
protected function registerServiceProvider(): void
{
$providersPath = base_path('bootstrap/providers.php');
if (File::exists($providersPath)) {
$content = File::get($providersPath);
$providerClass = "App\\Modules\\{$this->studlyName}\\{$this->studlyName}ServiceProvider::class";
if (!str_contains($content, $providerClass)) {
$content = preg_replace(
'/(\];)/',
" {$providerClass},\n$1",
$content
);
File::put($providersPath, $content);
$this->log("✓ Registered ServiceProvider");
}
} else {
$this->log("⚠ Could not auto-register ServiceProvider");
}
}
protected function getNextSteps(?string $branchName): array
{
$steps = [
"Run migrations: `php artisan migrate`",
"Seed permissions: `php artisan db:seed --class=RolePermissionSeeder`",
"Clear caches: `php artisan optimize:clear`",
"Access frontend: `/{$this->kebabName}`",
];
if ($branchName) {
$steps[] = "Push branch: `git push -u origin {$branchName}`";
$steps[] = "Create merge request when ready";
}
return $steps;
}
protected function log(string $message): void
{
$this->logs[] = $message;
}
}

View File

@@ -0,0 +1,77 @@
<?php
namespace App\Traits;
use OwenIt\Auditing\Auditable;
trait ModuleAuditable
{
use Auditable;
/**
* Get the audit configuration from module config.
*/
public function getAuditConfig(): array
{
$moduleName = $this->getModuleName();
return config("{$moduleName}.audit", [
'enabled' => true,
'strategy' => 'all',
'include' => [],
'exclude' => [],
]);
}
/**
* Determine if auditing is enabled for this model.
*/
public function isAuditingEnabled(): bool
{
$config = $this->getAuditConfig();
return $config['enabled'] ?? true;
}
/**
* Get fields to include in audit (if strategy is 'include').
*/
public function getAuditInclude(): array
{
$config = $this->getAuditConfig();
if (($config['strategy'] ?? 'all') === 'include') {
return $config['include'] ?? [];
}
return [];
}
/**
* Get fields to exclude from audit.
*/
public function getAuditExclude(): array
{
$config = $this->getAuditConfig();
return array_merge(
$this->auditExclude ?? [],
$config['exclude'] ?? []
);
}
/**
* Determine the module name from the model's namespace.
*/
protected function getModuleName(): string
{
$class = get_class($this);
// Extract module name from namespace: App\Modules\{ModuleName}\Models\...
if (preg_match('/App\\\\Modules\\\\([^\\\\]+)\\\\/', $class, $matches)) {
return \Illuminate\Support\Str::snake($matches[1]);
}
return 'app';
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class AppLayout extends Component
{
/**
* Get the view / contents that represents the component.
*/
public function render(): View
{
return view('layouts.app');
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\View\Components;
use App\Services\MenuService;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class FrontendMenu extends Component
{
public array $items = [];
public function __construct(
public string $menu = 'header',
public string $class = '',
) {
$menuService = app(MenuService::class);
$this->items = $menuService->getMenu($menu) ?? [];
}
public function render(): View
{
return view('components.frontend-menu');
}
public function hasItems(): bool
{
return count($this->items) > 0;
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\View\Components;
use App\Services\MenuService;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class FrontendMenuResponsive extends Component
{
public array $items = [];
public function __construct(
public string $menu = 'header',
public string $class = '',
) {
$menuService = app(MenuService::class);
$this->items = $menuService->getMenu($menu) ?? [];
}
public function render(): View
{
return view('components.frontend-menu-responsive');
}
public function hasItems(): bool
{
return count($this->items) > 0;
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class GuestLayout extends Component
{
/**
* Get the view / contents that represents the component.
*/
public function render(): View
{
return view('layouts.guest');
}
}

15
src/artisan Normal file
View File

@@ -0,0 +1,15 @@
#!/usr/bin/env php
<?php
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
$status = (require_once __DIR__.'/bootstrap/app.php')
->handleCommand(new ArgvInput);
exit($status);

21
src/bootstrap/app.php Normal file
View File

@@ -0,0 +1,21 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'registration.enabled' => \App\Http\Middleware\CheckRegistrationEnabled::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();

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

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

View File

@@ -0,0 +1,6 @@
<?php
return [
App\Providers\AppServiceProvider::class,
App\Providers\Filament\AdminPanelProvider::class,
];

82
src/composer.json Normal file
View File

@@ -0,0 +1,82 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.2",
"filament/filament": "^3.2",
"laravel/framework": "^11.31",
"laravel/sanctum": "^4.0",
"laravel/tinker": "^2.9",
"owen-it/laravel-auditing": "^14.0",
"spatie/flare-client-php": "^1.10",
"spatie/laravel-ignition": "^2.11",
"spatie/laravel-permission": "^6.24"
},
"require-dev": {
"czproject/git-php": "^4.6",
"fakerphp/faker": "^1.23",
"laravel/breeze": "^2.3",
"laravel/pail": "^1.1",
"laravel/pint": "^1.27",
"laravel/sail": "^1.26",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.1",
"pestphp/pest": "^3.8",
"pestphp/pest-plugin-laravel": "^3.2",
"phpunit/phpunit": "^11.0.1"
},
"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",
"@php artisan filament:upgrade"
],
"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",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite"
]
},
"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
}

11679
src/composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

126
src/config/app.php Normal file
View File

@@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'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
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => env('APP_TIMEZONE', 'UTC'),
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| 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' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];

115
src/config/auth.php Normal file
View File

@@ -0,0 +1,115 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| 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' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];

108
src/config/cache.php Normal file
View File

@@ -0,0 +1,108 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| 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: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'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' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_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, and 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_'),
];

173
src/config/database.php Normal file
View File

@@ -0,0 +1,173 @@
<?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 database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_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'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_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('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_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 on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| 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 Memcached. You may define your connection settings here.
|
*/
'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'),
],
],
];

View File

@@ -0,0 +1,80 @@
<?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 for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => 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,
'report' => 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'),
],
];

132
src/config/logging.php Normal file
View File

@@ -0,0 +1,132 @@
<?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 is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'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' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', env('LOG_STACK', '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' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'),
'emoji' => env('LOG_SLACK_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' => env('LOG_SYSLOG_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'),
],
],
];

116
src/config/mail.php Normal file
View File

@@ -0,0 +1,116 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| 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 that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url(env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'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 emails 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 emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
];

202
src/config/permission.php Normal file
View File

@@ -0,0 +1,202 @@
<?php
return [
'models' => [
/*
* When using the "HasPermissions" trait from this package, we need to know which
* Eloquent model should be used to retrieve your permissions. Of course, it
* is often just the "Permission" model but you may use whatever you like.
*
* The model you want to use as a Permission model needs to implement the
* `Spatie\Permission\Contracts\Permission` contract.
*/
'permission' => Spatie\Permission\Models\Permission::class,
/*
* When using the "HasRoles" trait from this package, we need to know which
* Eloquent model should be used to retrieve your roles. Of course, it
* is often just the "Role" model but you may use whatever you like.
*
* The model you want to use as a Role model needs to implement the
* `Spatie\Permission\Contracts\Role` contract.
*/
'role' => Spatie\Permission\Models\Role::class,
],
'table_names' => [
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'roles' => 'roles',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your permissions. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'permissions' => 'permissions',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your models permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_permissions' => 'model_has_permissions',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your models roles. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_roles' => 'model_has_roles',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'role_has_permissions' => 'role_has_permissions',
],
'column_names' => [
/*
* Change this if you want to name the related pivots other than defaults
*/
'role_pivot_key' => null, // default 'role_id',
'permission_pivot_key' => null, // default 'permission_id',
/*
* Change this if you want to name the related model primary key other than
* `model_id`.
*
* For example, this would be nice if your primary keys are all UUIDs. In
* that case, name this `model_uuid`.
*/
'model_morph_key' => 'model_id',
/*
* Change this if you want to use the teams feature and your related model's
* foreign key is other than `team_id`.
*/
'team_foreign_key' => 'team_id',
],
/*
* When set to true, the method for checking permissions will be registered on the gate.
* Set this to false if you want to implement custom logic for checking permissions.
*/
'register_permission_check_method' => true,
/*
* When set to true, Laravel\Octane\Events\OperationTerminated event listener will be registered
* this will refresh permissions on every TickTerminated, TaskTerminated and RequestTerminated
* NOTE: This should not be needed in most cases, but an Octane/Vapor combination benefited from it.
*/
'register_octane_reset_listener' => false,
/*
* Events will fire when a role or permission is assigned/unassigned:
* \Spatie\Permission\Events\RoleAttached
* \Spatie\Permission\Events\RoleDetached
* \Spatie\Permission\Events\PermissionAttached
* \Spatie\Permission\Events\PermissionDetached
*
* To enable, set to true, and then create listeners to watch these events.
*/
'events_enabled' => false,
/*
* Teams Feature.
* When set to true the package implements teams using the 'team_foreign_key'.
* If you want the migrations to register the 'team_foreign_key', you must
* set this to true before doing the migration.
* If you already did the migration then you must make a new migration to also
* add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions'
* (view the latest version of this package's migration file)
*/
'teams' => false,
/*
* The class to use to resolve the permissions team id
*/
'team_resolver' => \Spatie\Permission\DefaultTeamResolver::class,
/*
* Passport Client Credentials Grant
* When set to true the package will use Passports Client to check permissions
*/
'use_passport_client_credentials' => false,
/*
* When set to true, the required permission names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_permission_in_exception' => false,
/*
* When set to true, the required role names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_role_in_exception' => false,
/*
* By default wildcard permission lookups are disabled.
* See documentation to understand supported syntax.
*/
'enable_wildcard_permission' => false,
/*
* The class to use for interpreting wildcard permissions.
* If you need to modify delimiters, override the class and specify its name here.
*/
// 'wildcard_permission' => Spatie\Permission\WildcardPermission::class,
/* Cache-specific settings */
'cache' => [
/*
* By default all permissions are cached for 24 hours to speed up performance.
* When permissions or roles are updated the cache is flushed automatically.
*/
'expiration_time' => \DateInterval::createFromDateString('24 hours'),
/*
* The cache key used to store all permissions.
*/
'key' => 'spatie.permission.cache',
/*
* You may optionally indicate a specific cache driver to use for permission and
* role caching using any of the `store` drivers listed in the cache.php config
* file. Using 'default' here means to use the `default` set in cache.php.
*/
'store' => 'default',
],
];

112
src/config/queue.php Normal file
View File

@@ -0,0 +1,112 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_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' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_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', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];

84
src/config/sanctum.php Normal file
View File

@@ -0,0 +1,84 @@
<?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::currentRequestHost(),
))),
/*
|--------------------------------------------------------------------------
| 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' => Illuminate\Cookie\Middleware\EncryptCookies::class,
'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
],
];

38
src/config/services.php Normal file
View File

@@ -0,0 +1,38 @@
<?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.
|
*/
'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'),
],
'resend' => [
'key' => env('RESEND_KEY'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
];

217
src/config/session.php Normal file
View File

@@ -0,0 +1,217 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| 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 expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'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 to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined 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 session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'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're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain and all subdomains. Typically, this shouldn't be changed.
|
*/
'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. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_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" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_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' => env('SESSION_PARTITIONED_COOKIE', false),
];

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,49 @@
<?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();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};

View File

@@ -0,0 +1,35 @@
<?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('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->integer('expiration');
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->integer('expiration');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};

View File

@@ -0,0 +1,57 @@
<?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('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedTinyInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
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('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

View File

@@ -0,0 +1,25 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('menus', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->string('location')->nullable()->comment('e.g., header, footer, sidebar');
$table->boolean('is_active')->default(true);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('menus');
}
};

View File

@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('menu_items', function (Blueprint $table) {
$table->id();
$table->foreignId('menu_id')->constrained()->cascadeOnDelete();
$table->foreignId('parent_id')->nullable()->constrained('menu_items')->cascadeOnDelete();
$table->string('title');
$table->string('type')->default('link')->comment('link, module, route');
$table->string('url')->nullable()->comment('For external links');
$table->string('route')->nullable()->comment('For named routes');
$table->json('route_params')->nullable()->comment('Route parameters as JSON');
$table->string('module')->nullable()->comment('Module slug for permission checking');
$table->string('permission')->nullable()->comment('Specific permission required');
$table->string('icon')->nullable()->comment('Icon class or name');
$table->string('target')->default('_self')->comment('_self, _blank');
$table->integer('order')->default(0);
$table->boolean('is_active')->default(true);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('menu_items');
}
};

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('settings', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->text('value')->nullable();
$table->string('type')->default('string');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('settings');
}
};

View File

@@ -0,0 +1,134 @@
<?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
{
$teams = config('permission.teams');
$tableNames = config('permission.table_names');
$columnNames = config('permission.column_names');
$pivotRole = $columnNames['role_pivot_key'] ?? 'role_id';
$pivotPermission = $columnNames['permission_pivot_key'] ?? 'permission_id';
throw_if(empty($tableNames), Exception::class, 'Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');
throw_if($teams && empty($columnNames['team_foreign_key'] ?? null), Exception::class, 'Error: team_foreign_key on config/permission.php not loaded. Run [php artisan config:clear] and try again.');
Schema::create($tableNames['permissions'], static function (Blueprint $table) {
// $table->engine('InnoDB');
$table->bigIncrements('id'); // permission id
$table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
$table->string('guard_name'); // For MyISAM use string('guard_name', 25);
$table->timestamps();
$table->unique(['name', 'guard_name']);
});
Schema::create($tableNames['roles'], static function (Blueprint $table) use ($teams, $columnNames) {
// $table->engine('InnoDB');
$table->bigIncrements('id'); // role id
if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing
$table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable();
$table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');
}
$table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
$table->string('guard_name'); // For MyISAM use string('guard_name', 25);
$table->timestamps();
if ($teams || config('permission.testing')) {
$table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);
} else {
$table->unique(['name', 'guard_name']);
}
});
Schema::create($tableNames['model_has_permissions'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission, $teams) {
$table->unsignedBigInteger($pivotPermission);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
} else {
$table->primary([$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
}
});
Schema::create($tableNames['model_has_roles'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole, $teams) {
$table->unsignedBigInteger($pivotRole);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
} else {
$table->primary([$pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
}
});
Schema::create($tableNames['role_has_permissions'], static function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission) {
$table->unsignedBigInteger($pivotPermission);
$table->unsignedBigInteger($pivotRole);
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
$table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary');
});
app('cache')
->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
->forget(config('permission.cache.key'));
}
/**
* Reverse the migrations.
*/
public function down(): void
{
$tableNames = config('permission.table_names');
throw_if(empty($tableNames), Exception::class, 'Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.');
Schema::drop($tableNames['role_has_permissions']);
Schema::drop($tableNames['model_has_roles']);
Schema::drop($tableNames['model_has_permissions']);
Schema::drop($tableNames['roles']);
Schema::drop($tableNames['permissions']);
}
};

View File

@@ -0,0 +1,39 @@
<?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('audits', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('user_type')->nullable();
$table->unsignedBigInteger('user_id')->nullable();
$table->string('event');
$table->morphs('auditable');
$table->text('old_values')->nullable();
$table->text('new_values')->nullable();
$table->text('url')->nullable();
$table->ipAddress('ip_address')->nullable();
$table->string('user_agent', 1023)->nullable();
$table->string('tags')->nullable();
$table->timestamps();
$table->index(['user_id', 'user_type']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('audits');
}
};

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->text('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable()->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

View File

@@ -0,0 +1,19 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
$this->call([
RolePermissionSeeder::class,
MenuSeeder::class,
]);
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace Database\Seeders;
use App\Models\Menu;
use App\Models\MenuItem;
use Illuminate\Database\Seeder;
class MenuSeeder extends Seeder
{
public function run(): void
{
$headerMenu = Menu::firstOrCreate(
['slug' => 'header'],
[
'name' => 'Header Navigation',
'location' => 'header',
'is_active' => true,
]
);
MenuItem::firstOrCreate(
['menu_id' => $headerMenu->id, 'title' => 'Dashboard'],
[
'type' => 'route',
'route' => 'dashboard',
'icon' => 'heroicon-o-home',
'order' => 1,
'is_active' => true,
]
);
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\User;
class RolePermissionSeeder extends Seeder
{
public function run(): void
{
app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
// Core permissions
$corePermissions = [
'users.view',
'users.create',
'users.edit',
'users.delete',
'settings.manage',
'audit.view',
'menus.view',
'menus.create',
'menus.edit',
'menus.delete',
];
foreach ($corePermissions as $permission) {
Permission::firstOrCreate(['name' => $permission]);
}
// Auto-load module permissions from app/Modules/*/Permissions.php
$this->loadModulePermissions();
// Create roles
$adminRole = Role::firstOrCreate(['name' => 'admin']);
$adminRole->syncPermissions(Permission::all());
$editorRole = Role::firstOrCreate(['name' => 'editor']);
$editorRole->syncPermissions(['users.view', 'users.edit']);
$viewerRole = Role::firstOrCreate(['name' => 'viewer']);
$viewerRole->syncPermissions(['users.view']);
// Create admin user if not exists
$admin = User::firstOrCreate(
['email' => 'admin@example.com'],
[
'name' => 'Admin',
'password' => bcrypt('password'),
'email_verified_at' => now(),
]
);
$admin->assignRole('admin');
}
/**
* Scan all module Permissions.php files and register permissions.
*/
protected function loadModulePermissions(): void
{
$modulesPath = app_path('Modules');
if (!File::isDirectory($modulesPath)) {
return;
}
$modules = File::directories($modulesPath);
foreach ($modules as $modulePath) {
$permissionsFile = $modulePath . '/Permissions.php';
if (File::exists($permissionsFile)) {
$permissions = require $permissionsFile;
if (is_array($permissions)) {
foreach ($permissions as $permissionName => $description) {
// Handle both formats:
// ['permission.name' => 'Description'] or ['permission.name']
$name = is_string($permissionName) ? $permissionName : $description;
Permission::firstOrCreate(['name' => $name]);
}
}
}
}
}
}

2852
src/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

19
src/package.json Normal file
View File

@@ -0,0 +1,19 @@
{
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"devDependencies": {
"@tailwindcss/forms": "^0.5.2",
"alpinejs": "^3.4.2",
"autoprefixer": "^10.4.2",
"axios": "^1.7.4",
"concurrently": "^9.0.1",
"laravel-vite-plugin": "^1.2.0",
"postcss": "^8.4.31",
"tailwindcss": "^3.1.0",
"vite": "^6.0.11"
}
}

33
src/phpunit.xml Normal file
View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>app</directory>
</include>
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_STORE" value="array"/>
<!-- <env name="DB_CONNECTION" value="sqlite"/> -->
<!-- <env name="DB_DATABASE" value=":memory:"/> -->
<env name="MAIL_MAILER" value="array"/>
<env name="PULSE_ENABLED" value="false"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="TELESCOPE_ENABLED" value="false"/>
</php>
</phpunit>

6
src/postcss.config.js Normal file
View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

25
src/public/.htaccess Normal file
View File

@@ -0,0 +1,25 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Handle X-XSRF-Token Header
RewriteCond %{HTTP:x-xsrf-token} .
RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

File diff suppressed because one or more lines are too long

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