LARAVEL 8: Class 'Database\Seeders\DB' not found
16,743
Solution 1
That's because Laravel will look for DB class in the current namespace which is Database\Seeders.
Since Laravel has facades defined in config/app.php
which allows you to use those classes without full class name.
'DB' => Illuminate\Support\Facades\DB::class,
You can either declare DB class after the namespace declaration with
use DB;
or just use it with backslash.
\DB::table('users')->insert([
Solution 2
In the UserSeeder Class add:
use Illuminate\Support\Facades\DB;
Author by
Admin
Updated on June 14, 2022Comments
-
Admin almost 2 years
I'm working with seeder to fill my
users
table, so I created a new seeder calledUserSeeder
and then I added these codes to it:public function run() { foreach(range(1,10) as $item) { DB::table('users')->insert([ 'name' => "name $item", 'email' => "email $item", 'email_verified_at' => now(), 'password' => "password $item" ]); } }
After that I tried
php artisan db:seed --class=UserSeeder
but it shows me:Error
Class 'Database\Seeders\DB' not found
which is related to this line:
DB::table('users')->insert([
So why it is not found there, what should I do now?
-
lagbox over 3 yearsnamespacing, you would have to import/alias the
DB
class to use it in that file like that -
Admin over 3 years@lagbox Would you please tell me where is it and what should I write?
-
lagbox over 3 years
use DB;
after the namespace declaration -
Tohid Dadashnezhad over 3 yearsI had this problem too and I solved this issue by running
composer dump-autoload
after creating a new seeder class or changing its namespace.
-
-
The Only Smart Boy over 3 yearsThe declaration approach is always the recommended option as it allows you to use the object / class as many times as you want while calling the full class path and name every time you want to use causes a lot of confusion and may be difficult to track in case of errors
-
olle.holm about 3 yearsWhen using this suggestion the autocomplete also worked for me in Visual studio code.