在laravel中是否有initalSetup()函数或类似的东西?

时间:2016-05-30 16:23:55

标签: php laravel laravel-5

我在Laravel中开发了一个应用程序(我使用此插件添加角色/权限https://github.com/Zizaco/entrust

我需要在第一次使用应用程序时使用Laravel为我的应用程序创建一些基本数据(一些角色和权限),这些数据不应每次都创建。

我无法找到我可以使用的功能或事件。 我试图避免这样做:

if(role is not created)
    create it
else
    do nothing

1 个答案:

答案 0 :(得分:1)

通过创建播种机来设置基本应用数据或播种:

php artisan make:seeder RolesTableSeeder

它将生成database/seeder/RolesTableSeeder.php,打开该文件然后插入您的初始角色,这是示例:

use Illuminate\Database\Seeder;

class RolesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('roles')->truncate();

        $roles = [
            [
                'id' => 1,
                'name' => 'Administrator',
                'slug' => 'admin',
                'created_at' => \Carbon\Carbon::now(),
                'updated_at' => \Carbon\Carbon::now(),
            ],
            [
                'id' => 2,
                'name' => 'Moderator',
                'slug' => 'moderator',
                'created_at' => \Carbon\Carbon::now(),
                'updated_at' => \Carbon\Carbon::now(),
            ],
        ];

        DB::table('roles')->insert($roles);
    }
}

然后在DatabaseSeeder类注册播种机:

public function run()
{
    ...

    $this->call(RolesTableSeeder::class);
}

最后运行php artisan db:seed,对其他表执行相同操作。

如果您想插入假数据等虚假数据用于测试目的,请使用model factories