Reputation: 345
I am struggling with PHP Namespaces
and Auto loading
in Laravel 5.4
. I actually decided to put the models that I need to use in a definite and named folder as app/Models
:
php artisan make:model Models/Customer
I have set Customer model's namespace to namespace Models;
Then, I created a route as follows:
Route::get('customer', function () {
$customer = \App\Models\Cutomer::find(1);
echo $customer;
});
To do auto loading work I opened the composer.json
file located in the very root folder of the Laravel
project and made the autoload
to be as follows:
"autoload": {
"classmap": [
"database",
"app/Models"
],
"psr-4": {
"App\\": "app/",
"App\\Models\\": "App/Models"
}
},
After all of this I checked if my composer is an update version and ran dump-autoload
:
composer self-update
composer dump-autoload -o
There is also worth of notice the contents of vendor/composer/autoload_classmap.php
:
'App\\Models\\Customer' => $baseDir . '/app/Models/Customer.php',
'App\\Models\\Test\\Test' => $baseDir . '/app/Models/Test.php',
My problem is that whenever I execute the url: http://127.0.0.1:8000/customer
I will encounter the following error output:
(1/1) FatalThrowableError
Class 'App\Models\Cutomer' not found
Would you please help me understand where of my work has been incorrect, and how to fix it? Thank you very much in advance.
Upvotes: 0
Views: 2138
Reputation: 14620
First, you have an error in your PSR-4 setup.
"App\\Models\\": "App/Models"
This does not map to a valid directory. Secondly, and more importantly, there is no need to autoload a nested namespace of one that is already declared. By autoloading App
you will already autoload any nested namespaces as long as they conform to PSR-4 standards i.e namespace as directory name and filename as class name.
Composer setup only needs to be the following:
"psr-4": {
"App\\": "app/"
}
Upvotes: 1
Reputation: 35180
The namespace in the model should be namespace App\Model;
(hence why you call the class as \App\Models\Cutomer
)
When you use php artisan make:model Models/Customer
it should have set the namespace correctly then.
Also, you don't need to edit your composer.json
to do this. Remove the additions you've made to your composer.json
file for the autoloading and then run composer dumpautoload
from the command line.
Hope this helps!
Upvotes: 1