Why am I getting a “class not found” error in my L

2019-01-28 11:45发布

问题:

I am using "laravel/framework": "4.2. *" version, and I want to use the module system for my project. I have followed the instructions provided in this document.

I can create modules by using the command: php artisan modules:create module_name. I have created an admin module in my app directory, and the module's directory structure has been created.

I am using DB::select('some SQL statement') in one of the actions of the controller from the admin module, but it is giving me the following error:

Class 'App\Modules\Admin\Controllers\DB' not found.

Why is it not able to find this class?

回答1:

When using DB or any other Laravel facades outside the root namespace, you need to make sure you actually use the class in the root namespace. You can put a \ before the class.

\DB::select(...)

Or you can use the use keyword in your class file to allow the use of a different namespaced class without explicitly writing out the namespace each time you use it.

<?php namespace App\Modules\Admin\Controllers;

use DB;
use BaseController;

class ModuleController extends BaseController {

    public function index()
    {
        // This will now use the correct facade
        $data = DB::select(...);
    }
}

Note that the use keyword always assumes it is loading a namespace from the root namespace. Therefore a fully qualified namespace is always required with use.



回答2:

or else you can use autoload in composer.json

"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php"
    ]
},