Route to controller in subfolder in Laravel 5

2019-04-22 18:51发布

问题:

This is my routes.php:

Route::get('/', 'Panel\PanelController@index');

This is my folders:

Http/
....Controllers/
................Panel/
....................../PanelController.php

This is my Controller:

namespace App\Http\Controllers;

class PanelController extends Controller {

/* some code here... */

}

This is what I get:

Class App\Http\Controllers\Panel\PanelController does not exist

I tried the "composer dump-autoload" command but still not working...

回答1:

The namespace of your class has to match the directory structure. In this case you have to adjust your class and add Panel

namespace App\Http\Controllers\Panel;
//                             ^^^^^

use App\Http\Controllers\Controller;

class PanelController extends Controller {

/* some code here... */

}


回答2:

Follow three simple steps

  1. append the folder name in the namespace

    namespace App\Http\Controllers\Panel;
    
  2. Add "use App\Http\Controllers\Controller;" to the controller before the class definition

    namespace App\Http\Controllers\Panel;
    use App\Http\Controllers\Controller;
    
  3. Add the appended folder name when invoking the controller in any route

    Route::get('foo','Panel\PanelController@anyaction');
    

There is no need to run "composer dump-autoload"



回答3:

You can generate a controller with a subfolder as simple as:

php artisan make:controller Panel\PanelController

It automatically creates proper namespaces and files with directory. And reference it in routes just as mentioned before:

Route::get('/some','Panel\PanelControllder@yourAction');

Happy codding!