Because of my work at developerjoy.co, I have created over 10 Laravel projects from scratch in the last year, and worked on more than 25 and I have seem one common thing in all of them.
The Laravel default directory structure only works when your project it's really small.
As the project grows, the default directory structure becomes a problem because it does not scale properly.
After a few use cases, models, policies, and so on, you will end with something similar to this:
app/ ├── Actions │ ├── Actionable.php │ ├── Graph │ │ └── ... │ ├── MonthlyResume │ │ └── GenerateMonthlyResumeAssets.php │ ├── User │ │ └── UpdateUser.php │ └── VoidActionable.php ├── Console │ ├── Commands │ │ ├── CalculateUserCryptoPortfolioBalanceCommand.php │ │ ├── CategorizeTransactionsIaCommand.php │ │ ├── GenerateMonthlyReportAssetsCommand.php │ │ ├── IdeHelperAllCommand.php │ │ ├── PruneNotificationsCommand.php │ │ ├── SendMonthlyReportNotificationCommand.php │ │ ├── SendNewUpdateChangeLogNotificationCommand.php │ │ └── TrainCategorizationIaCommand.php │ └── Kernel.php ├── Contracts │ └── Pipe.php ├── Events │ ├── SharingConfigurationSaved.php │ ├── SupportMessageCreated.php │ └── VisitIncreased.php ├── Exceptions │ ├── GetBankAccountTransactionError.php │ ├── Handler.php │ └── RenderableApiError.php ├── Http │ ├── Controllers │ │ ├── Banks │ │ ├── Controller.php │ │ ├── CryptoCurrency │ │ ├── Notification │ │ ├── SupportMessage │ │ └── User │ │ ├── DeleteUserController.php │ │ ├── GetUserController.php │ │ └── PutUserController.php │ ├── Kernel.php │ ├── Middleware │ │ ├── Authenticate.php │ │ ├── DefaultLocale.php │ │ ├── TrustProxies.php │ │ ├── ValidateSignature.php │ │ └── VerifyCsrfToken.php │ ├── Requests │ │ ├── PostSupportMessageRequest.php │ │ └── PutUserRequest.php │ └── Resources ├── Jobs │ ├── CalculateUserCryptoPortfolioBalanceJob.php │ ├── GenerateMonthlyResumeAssetsJob.php │ ├── GetBankAccountDetails.php │ └── GetCoinGeckoValuesJob.php ├── Listeners │ ├── SendAdminNotificationOnSupportMessageCreated.php │ ├── SendEmailToUserOnVisitIncremented.php │ └── SendMailOnSupportMessageCreated.phpphp ├── Mail │ ├── SupportMessage │ └── Visits ├── Models │ ├── Bank.php │ ├── SharingConfiguration.php │ ├── SupportMessage.php │ ├── User.php │ └── UserCryptoPortfolioBalance.php ├── Notifications │ ├── Notifiable.php │ ├── ThrottledNotification.php │ ├── UncategorizedTransactionNotification.php │ └── UpdateChangeLogNotification.php ├── Policies │ └── CryptoCurrencyOrderPolicy.php ├── Providers │ ├── AppServiceProvider.php │ ├── EventServiceProvider.php │ ├── HorizonServiceProvider.php │ └── RouteServiceProvider.php ├── Services │ └── CategorizationAi.php └── Support ├── OrderType.php ├── SafeNumberFromStringParser.php ├── ShortNumberFormatter.php ├── StockAssets └── helpers.php
I removed a lot of files and directories from tree, but you can imagine that it's impossible to see all the code related to users.
As you can see, it's really difficult to know what's happening there. You are working in a users controller, for example, and you don't have all the relevant classes close to it.
You can't see, at a glance, all the relevant classes and models for your current use case.
A better directory structure in our Laravel project
The main key, to properly scale your app, is to being able to see al the related code to the current use case you're working on at a glance.
For example, if you're working on the user registration use case, you should have the user model, user policies, registration request, the registered event, and more, close to you.
src/ ├── Leads ├── Teams └── Users ├── Actions │ ├── CreateUser │ │ ├── CreateUser.php │ │ └── CreateUserAction.php │ ├── LoginUserAction.php │ ├── LogoutUserAction.php │ └── RefreshAuthenticationTokenAction.php ├── Authenticatable.php ├── Authentication.php ├── Events │ └── UserRegistered.php ├── Http │ ├── Controllers │ │ └── Api │ │ ├── PostAuthenticationLoginApiController.php │ │ ├── PostAuthenticationLogoutApiController.php │ │ ├── PostAuthenticationRefreshApiController.php │ │ └── PostAuthenticationRegisterApiController.php │ ├── Requests │ │ ├── PostAuthenticationLoginRequest.php │ │ └── PostUserRequest.php │ └── routes │ └── api.php ├── Infrastructure │ └── UserEventServiceProvider.php ├── InvalidCredentials.php ├── Listeners │ └── SendWelcomeEmailOnUserRegistered.php ├── Mail │ └── WelcomeMail.php └── User.php
But know, you're wondering, how can I achieve this architecture easily on Laravel.
How to implement a domain directory architecture on Laravel
The start point is composer.json file. We are going to create a new folder ./src to store all our new code.
Adding the directory to the psr-4 key in the composer.json we are going to autoimport all our files easily.
"autoload": { "psr-4": { "App\\": "app/", "DeveloperJoy\\": "src/", // ... }, // ... }
Just with this, you can put all your models, controllers, requests, policies, and more, in a custom domain folder under src/User, for example.
There are only a few things missing: routes, and providers, so let's go one by one.
Move routes to a custom folder
For routes we have multiple options, for me, the most simpler and easier is to import them in the web.php or in the api.php file.
I usually write a helper file inside routes folder that looks like this:
<?php function domain_web_routes(string $domain): void { require __DIR__."/../src/{$domain}/Http/routes/web.php"; } function domain_api_routes(string $domain): void { require __DIR__."/../src/{$domain}/Http/routes/api.php"; }
and imported in my composer.json file just adding it to the files array.
"autoload": { // ... "files": [ "routes/helpers.php" ] },
A them, in my default web.php or api.php I just import each new domain folder when it has any route.
This is, for example, my web.php file:
<?php use Illuminate\Support\Facades\Route; Route::inertia('/', 'Welcome'); domain_web_routes('Leads');
Inside src/Leads/Http/routes y have a web.php file with all my routes related to leads.
Is really that simple.
Move service providers, to a custom domain folder
With providers is actually pretty easy.
We have a file under bootstrap/app.php that has an array of all our providers.
You just have to add new providers to it, and it will be processed automatically on load time.
return Application::configure(basePath: dirname(__DIR__)) ->withProviders([ DeveloperJoy\Users\Infrastructure\UserEventServiceProvider::class, ]) ->create();
The above is the detailed content of How to organize your Laravel Project in 4. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.