Changing Laravel’s App Directory
If you’re like me and you prefer to have the freedom to create your applications the way you want, you’ve probably gotten a bit annoyed with the way Laravel insists on managing your directory structure for you.
I’m talking, of course, about the “app” directory. The one where everything you write for your application lives. Why should I be forced to structure my files in a way that can quickly become inefficient, unproductive and messy.
Say you want to develop an api for a mobile app, you might decide that you want to contain all your api code in a different folder structure, and namespace your files by feature. For example:
src/Product/Feature
Well, you’ll need to define the new namespace in your composer.json
file:
"autoload": {
"psr-4": {
"Product\\": "src/Product"
},
...
}
If you are going to use this directory for all your controller routes, you’ll want to update the $namespace
property in RouteServiceProvider
:
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'Product';
Now that we’ve got these basics down, we need to tell Laravel that we want to use the src/Product
path for all of our files. Laravel’s container ships with a useAppPath
method which isn’t used by default. in bootstrap/app.php
append the following before the return statement:
$app->useAppPath(realpath(__DIR__ . '/../src/Product'));
After this, when you run Laravel’s make command (e.g. php artisan make:model
) Laravel will automatically create them in this directory.