I\'m new to Laravel. To try and keep my app organized I would like to put my controllers into subfolders of the controller folder.
controllers\\
---- folder1
I am using Laravel 4.2. Here how I do it:
I have a directory structure like this one:
app
--controllers
----admin
------AdminController.php
After I have created the controller I've put in the composer.json the path to the new admin directory:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/controllers/admin",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
},
Next I have run
composer dump-autoload
and then
php artisan dump-autoload
Then in the routes.php I have the controller included like this:
Route::controller('admin', 'AdminController');
And everything works fine.
In Laravel 5.6, assuming the name of your subfolder' is Api
:
In your controller, you need these two lines:
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
And in your route file api.php
, you need:
Route::resource('/myapi', 'Api\MyController');
Add your controllers in your folders:
controllers\
---- folder1
---- folder2
Create your route not specifying the folder:
Route::get('/product/dashboard', 'MakeDashboardController@showDashboard');
Run
composer dump-autoload
And try again
If you're using Laravel 5.3 or above, there's no need to get into so much of complexity like other answers have said.
Just use default artisan command to generate a new controller.
For eg, if I want to create a User
controller in User
folder.
I would type
php artisan make:controller User/User
In routes,
Route::get('/dashboard', 'User\User@dashboard');
doing just this would be fine and now on localhost/dashboard is where the page resides.
Hope this helps.
For Laravel 5.3 above:
php artisan make:controller test/TestController
This will create the test
folder if it does not exist, then creates TestController
inside.
TestController
will look like this:
<?php
namespace App\Http\Controllers\test;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class TestController extends Controller
{
public function getTest()
{
return "Yes";
}
}
You can then register your route this way:
Route::get('/test','test\TestController@getTest');
Just found a way how to do it:
Just add the paths to the /app/start/global.php
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/controllers/product',
app_path().'/models',
app_path().'/database/seeds',
));