Reputation: 61
I am new to Laravel 5.
I set the original app up and running in Homestead. When I wrote a simple UserTableSeeder and tried to seed the MYSQL database using artisan, a error popped out: "Class User not found".
Well, I did not change anything in the "app/User.php" file and after I added the namespace App to the seeder code,
that is, from
User::create(array(..));
to
App\User::create(array(..));
the seeding worked just fine.
Same thing happened when I was trying to use
User::all();
or other Eloquent query operations in "routes.php". Only when I added the namespace App\ would it work out.
I have tried composer dump-autoload and I made sure the app name and the "composer.json" file was exactly the same as the original code in Laravel 5.
Do we have to add the namespace App/ whenever we want to use the models in Laravel 5?
I think I might have got something wrong because in Laravel 4 we do not have to add the namespace App in these cases.
Upvotes: 3
Views: 4131
Reputation: 16333
In Laravel 5, the app
directory is namespaced under App
by default. If you look in your composer.json
you will see that the app
directory is set up for psr-4 autoloading:
"psr-4": {
"App\\": "app/"
},
When you want to use a class from there or inside a subdirectory, you need to include the namespace. You can also use
it if you want to just reference the class name as is. For example:
app/Namespace/SomeClass.php
<?php namespace App\Namespace;
use App\User;
class SomeClass {
public function someMethod()
{
$user = User::find(1);
}
}
Upvotes: 6