Routing in Laravel 5 error

 ̄綄美尐妖づ 提交于 2020-01-06 14:09:56

问题


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


来源:https://stackoverflow.com/questions/29707320/routing-in-laravel-5-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!