Laravel能否修改目录结构?关于文件便捷复用的疑问与诉求
Hey there! Let’s tackle your two questions one by one—first about customizing Laravel’s directory structure, then why your original question might have gotten downvotes.
Absolutely! Laravel is built to be flexible, and customizing its directory layout is fully supported. Your idea of grouping related files (models, migrations, and their dependencies) together for easier cross-project reuse is actually a common, practical approach for modular development.
Here’s a step-by-step way to implement this:
- Create a modular structure, like
app/Modules/Post, where you’ll keep all Post-related files in one place:Post.php(your model file)Migrations/2024_05_20_000000_create_posts_table.php(the corresponding migration)- You can even add controllers, request classes, or seeders here if they’re tied to the model
- Update your
composer.jsonto ensure Laravel autoloads these new modules correctly:
Run"autoload": { "psr-4": { "App\\": "app/", "App\\Modules\\": "app/Modules/" } },composer dump-autoloadafterward to apply the autoload changes. - Tell Laravel where to find your custom migration files. You have two easy options:
- Specify the path directly when running migrations:
php artisan migrate --path=app/Modules/Post/Migrations - Add a custom command in
AppServiceProviderto run all module migrations at once:
Now you can runuse Illuminate\Support\Facades\Artisan; public function boot() { Artisan::command('migrate:modules', function () { $this->call('migrate', [ '--path' => app_path('Modules/*/Migrations'), ]); }); }php artisan migrate:modulesto execute all migrations across your modules.
- Specify the path directly when running migrations:
Downvotes on Stack Overflow don’t always mean your question isn’t serious—here are some common reasons this could happen:
- Unclear problem framing: If your original question didn’t explicitly lay out your pain point (needing to track down scattered files to reuse a model) or what you’d already tried, voters might have seen it as too vague.
- Perceived as opinion-based: Phrases like "I think this would be more reasonable" can sometimes come off as asking for preference debates, even though your core need is a technical solution.
- Potential duplicate content: There might already be existing questions about customizing Laravel’s directory structure, and voters felt your question didn’t add new context or specificity.
The fix? Reframe your question to focus on your concrete technical goal: "How can I group Laravel models with their migration files to simplify reuse across projects?" This makes it clear you’re solving a specific problem, not just debating preferences.
内容的提问来源于stack exchange,提问作者user7646471

