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)
For ** Laravel 5 or Laravel 5.1 LTS both **, if you have multiple Controllers in Admin folder, Route::group will be really helpful for you. For example:
<?php namespace App\Http\Controllers\Api\V1;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PostApiController extends Controller {
...
In My Route.php, I set namespace group to Api\V1 and overall it looks like:
The routes in "routes/web.php" file would be as below
/* All the Front-end controllers routes will work under Front namespace */
Route::group(['namespace' => 'Front'], function () {
Route::get('/home', 'HomeController@index');
});
And for Admin section, it will look like
/* All the admin routes will go under Admin namespace */
/* All the admin routes will required authentication,
so an middleware auth also applied in admin namespace */
Route::group(['namespace' => 'Admin'], function () {
Route::group(['middleware' => ['auth']], function() {
Route::get('/', ['as' => 'home', 'uses' => 'DashboardController@index']);
});
});
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.
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";
}
}
Organize your controllers in subfolder as you wish:
controller
---folder-1
------controllerA
------controllerB
---folder-2
------controllerC
------controllerD
use the controllers in the route file
use App\Http\controllers\folder-1\controllerA;
.....etc
Write your routes as normal
Route::get('/xyz', [controllerA::class, 'methodName']);