Summer Sale! All accounts are 50% off this week.

4xjbh's avatar

DB::table undefined function in Database Seeder

My seeder is not running as the method 'table' in the DB facade is undefined, refer below. I am having trouble resolving why?

(L5.1)

DB:table($table)->truncate();
<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder{

    protected $toTruncate = ['articles'];

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

      foreach ($this->toTruncate as $table) {

           DB::table($table)->truncate();
       }

        Model::reguard();
    }
}
0 likes
6 replies
4xjbh's avatar

I had tried Use DB; but it did not work. Why does \DB::table work? I was just using what Jeff was doing in 'Database Seeding and Model Factories' @ time 5:40.

bimalshah72's avatar
Level 6

@4xjbh There are several ways for accessing Facade.

'DB' is alias of 'Illuminate\Support\Facades\DB', .. check in config/app.php

hence \DB means '\Illuminate\Support\Facades\DB' - fully qualified name space.

Laravel 5 uses psr-4 class loading where you need fully qualified class names.

see .. http://www.php-fig.org/psr/psr-4/ hence first '' means it starts searching from root namespace- and includes vendor packages. If you remove '' then it searches in your own package and didn't get Illuminate\Support\Facades\DB.

1 like
yokisitumorang's avatar

Hi ! i have same problem when config database seed in laravel, you cannot use use DB or use\DB,,

you must spesified the path of your library :

you can use this -> use \Illuminate\Support\Facades\DB;

that solve my problem.

1 like
vishal_mohan's avatar

@yokisitumorang , and @4xjbh in latest version 8 of lumen you can ad alias of this -> use \Illuminate\Support\Facades\DB in bootstrap/app.php

$app->withFacades(

true, // $aliases parameter set to true (default)
[
    'Illuminate\Support\Facades\DB' => 'FacadesDB'
]);

And use as FacadesDB every where

1 like

Please or to participate in this conversation.