12

I'm working with seeder to fill my users table, so I created a new seeder called UserSeeder 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?

asked Oct 17, 2020 at 20:10
4
  • namespacing, you would have to import/alias the DB class to use it in that file like that Commented Oct 17, 2020 at 20:12
  • @lagbox Would you please tell me where is it and what should I write? Commented Oct 17, 2020 at 20:14
  • use DB; after the namespace declaration Commented Oct 17, 2020 at 20:16
  • I had this problem too and I solved this issue by running composer dump-autoload after creating a new seeder class or changing its namespace. Commented Oct 18, 2020 at 9:38

3 Answers 3

40

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([
answered Oct 18, 2020 at 12:11

1 Comment

The 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
10

In the UserSeeder Class add:

use Illuminate\Support\Facades\DB;

answered Jan 19, 2021 at 9:15

1 Comment

When using this suggestion the autocomplete also worked for me in Visual studio code.
0

I have fixed same error in Laravel 9 by importing

use Illuminate\Database\Seeder;
Reynadan
6686 silver badges19 bronze badges
answered Dec 16, 2022 at 22:04

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.