Ronald
Ronald

Reputation: 69

Laravel reseeding a table

In Laravel how would you reseed a database? Without losing existing data / migrations?

I have a RoleAndPermissionSeeder.php with Spatie's Permission package:

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class RoleAndPermissionSeeder extends Seeder
{
    public function run()
    {
        // Reset cached roles and permissions
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        $permissions = [
            'articles create',
            'articles delete',
            'articles read',
            'articles update',
            'dashboard read',
        ];

        foreach ($permissions as $permission) {
            Permission::create(['name' => $permission]);
        }
        // =======================================================================

        $admin = Role::create(['name' => 'admin']);
        $member = Role::create(['name' => 'member']);
        Role::create(['name' => 'super-admin']);

        // =======================================================================

        $admin_permissions = [
            'articles read',
            'dashboard read',
        ];

        $member_permissions = [
            'dashboard read',
        ];

        $admin->syncPermissions($admin_permissions);
        $member->syncPermissions($member_permissions);
    }
}

After creating a new migration for a blog I have added extra permissions to read, update the blog and so on. How would I reseed this file so that the new permissions get added?

Upvotes: 2

Views: 651

Answers (1)

IGP
IGP

Reputation: 15859

If your seeder class has firstOrCreate instead of create

foreach ($permissions as $permission) {
    Permission::firstOrCreate(['name' => $permission]);
}
// =======================================================================
$admin = Role::firstOrCreate(['name' => 'admin']);
$member = Role::firstOrCreate(['name' => 'member']);
Role::firstOrCreate(['name' => 'super-admin']);

It will not duplicate the data. If syncPermissions uses sync behind the scenes, then it shouldn't be a problem.

As long as you don't drop the table, you shouldn't lose any data.

Upvotes: 3

Related Questions