Search code examples
phplaravelcomposer-phplaravel-5psr-4

How to keep seeder files separate and clean in laravel?


I want to keep my seeder files separate. for example UsersTableSeeder.php , PostsTableSeeder.php and then call them in main seeder file (DatabaseSeeder.php) :

Example:

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{

    public function run()
    {
         $this->call(UsersTableSeeder::class);
         $this->call(PostsTableSeeder::class);
    }
}

usersTableSeeder.php :

<?php namespace App\Seeds;

    use Illuminate\Database\Seeder;
    use App\User;

    class UserTableSeeder extends Seeder {

        public function run()
        {
            //DB::table('users')->delete();

            // user1
            User::create(array(
                'name' => 'ahmad',
                'email' => '[email protected]',
                'password' => 'ahmad'
            ));
        }
    }

my UsersTableSeeder.php and PostsTableSeeder.php files are in the same directory that DatabaseSeeder.php is.

should I use psr-4 autoloading ? how?


Solution

  • Composer.json configuration

    composer.json has a autoload key to configure additional autoload paths.
    You can give it a try:

    
        "autoload": {
            "psr-4": {
                "App\\": "app/"
            },
            "classmap": [
                "database/seeds",
                "database/factories"
            ]
        }
    

    Example from my composer.json

    Remove the namespace line from your seeder classes. They are found by the classmap entries now.

    Explicit namespaces

    OR

    Keep the namespaces and add them in calls to ->call().
    Wherever you write a classname you can fully qualify the class with its namespace (should be \database\seeds\YourClass::class, which can depend on your composer.json settings), or add a use statement at the beginning of the file.