imperium2335
imperium2335

Reputation: 24112

Laravel 5 Model namespace class not found

I am trying to store my models in a custom namespace and directory structure as shown here:

enter image description here

I have:

namespace Modules\Core;

use App\Http\Controllers\Controller;

class TestController extends Controller {

    public function index(){
        $user = new User;
        return view('core::test');
    }

}

But I am getting:

FatalErrorException in TestController.php line 8:
Class 'Modules\Core\User' not found

Which is wrong anyway, so I thought it must be 'Modules\Core\Models\User'. I tried this and I still got the same error (just with a different class name).

My model:

namespace Modules\Core;

use Illuminate\Database\Eloquent\Model as Eloquent;

class User Extends Eloquent {
    protected $table = 'users';
}

How can I get access to this model in the TestController?


Route::group(array('namespace' => 'Modules\Core\Controllers'), function() {
    Route::get('/test', ['uses' => 'TestController@index']);
});

Upvotes: 3

Views: 11676

Answers (3)

Skywalker
Skywalker

Reputation: 1774

I had the same problem as above. In my case I had the following namespace:

namespace Modules\XMLApi;

I got the same error as above. When I changed the namespace to the following:

namespace Modules\XmlApi;

Then run the following command: composer dump-autoload

Then it worked.

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

You should edit your routes.php file:

Route::group(array('namespace' => 'Modules\Core\Controllers'), function() {
    Route::get('/test', ['uses' => '\Modules\Core\TestController@index']);
});

to use full together with namespace

Upvotes: 0

Joel Hinz
Joel Hinz

Reputation: 25384

If your controller is stored in Modules/Core/Controllers, the namespace should be namespace Modules\Core\Controllers;

And likewise, if the model is stored in Modules/Core/Models, its namespace is namespace Modules\Core\Models;

Then, in the controller, import it before using it:

<?php namespace Modules\Core\Controllers;

use Modules\Core\Models\User;
use App\Http\Controllers\Controller;

class TestController extends Controller {

    public function index(){
        $user = new User;
        return view('core::test');
    }

}

Upvotes: 3

Related Questions