Laravel Controller Subfolder routing
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
---- folder2
I tried to route to a controller, but laravel doesn't find it.
Route::get('/product/dashboard', 'folder1.MakeDashboardController@showDashboard');
What am I doing wrong?
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');
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
For those using Laravel 5 you need to set the namespace for the controller within the sub-directory (Laravel 5 is still in development and changes are happening daily)
To get a folder structure like:
Http
----Controllers
----Admin
PostsController.php
PostsController.php
namespace Admin\PostsController.php file like so:
<?php namespace App\Http\Controller\Admin;
use App\Http\Controllers\Controller;
class PostsController extends Controller {
//business logic here
}
Then your route for this is:
$router->get('/', 'Admin\PostsController@index');
And lastly, don't for get to do either composer or artisan dump
composer dump-autoload
or
php artisan dump