Routing in Laravel 5 error

2019-09-03 12:39发布

问题:

Routing in Laravel5 seems to be a major problem for me.

I was hoping to follow this example using the composer mapping

https://mattstauffer.co/blog/upgrading-from-laravel-4-to-laravel-5#namespacing-controllers

To avoid any issues with models or facades.

But when I route to this:

Route::get('school/test', 'school\SchoolController@index');

Error

    ReflectionException in Container.php line 776: Class school\SchoolController does not exist

The SchoolController is in the HTTP/controllers/school folder:

  namespace School
  class SchoolController extends Controller{
     public function index() {
        return "hello";
     }
 }

RouteServiceProvider:

 protected $namespace=NULL

composer is set for the HTTP/controllers

 "classmap": [
        "database",
        "app/Models",
        "app/HTTP/Controllers"

    ]

and works with routes such as this:

Route::resource('courses', 'CourseController');

So the router is just not finding files in a subfolder. I wonder what the problem is?

It seems the only option is

 RouteServiceProvider

  protected $namespace = 'App\Http\Controllers';

Composer.json

  `"classmap": [
        "database",
        "app/Models"        
    ],

HomeController in the App\Http\Controllers;

 namespace App\Http\Controllers;
 use App\Models\Course;

 class HomeController extends Controller {
 public function index()
 {
    $courses =Course::orderBy('created_at','DESC')->with('school')->paginate(12);

 }

But this means I need to add 'use App/...' for over 100 controller files, with varying models!

I appreciate help so far but I'm really looking for method one if possible, as two will involve placing all the model maps in each controller (lots of code). Unless there is a global way to map all the models in one file?

Someone suggested Alias but this doesn't work.

To re-iterate the issue. Routing fails for Controllers subfolders using composer for mapping

回答1:

Laravel will by default search for controllers in App\Http\Controllers. You can change that namespace by editing App\Providers\RouteServiceProvider:

protected $namespace = 'App\Http\Controllers';

In your case, since you want no "base namespace" at all, set it to null:

protected $namespace = null;

  1. Created directory structure: app/Controllers/Folder (the names don't really matter as long as they match with the rest)
  2. Created controller in Folder: TestController.php (namespace Folder;)
  3. Edited autoload > classmap in composer.json and added "app/Controllers"
  4. Run composer dump-autoload