Eloquent Seeder - only add if data doesn't exist

4.5k views Asked by At

I have a table called permissions; this is like the different roles a user can have. As the project grows, I may add more functionalities, therefore more permissions are created.

I have a PermissionSeeder.php that I would like to keep on adding the permissions that I add. Then every time a new permission is added, I would like to run the seeder on it. But, the existing entries should not be created.

I was thinking of truncating the table on every update, but then permission_id on the other pivot tables will conflict since they are the foreign keys.

This is what I was going to do at the moment:

use Permission;
class PermissionSeeder extends Seeder {

    public function run()
    {
        $permissions = [...]; // this is the array of ALL permissions that will keep on growing

        foreach ($permissions as $permission) {
            $model = Permission::whereName($permission['name']);
            if ($model->count() <= 0) {
                DB::table('permissions')->insert($permission);
            }
        }
    }
}

Is there a better practice?

1

There are 1 answers

0
Steve Bauman On BEST ANSWER

You could use firstOrCreate($permission) on your Permission model instead? This would eliminate some code for you.

foreach($permissions as $permission) {

    Permission::firstOrCreate($permission);

}

Keep in mind you'll need to set your protected $fillable; attribute inside your model to allow your fields to be mass assigned.

EDIT: You could also store your permissions inside a config file in your project so it's easier to access. Seems like a more natural place to put it rather than static inside the code itself.

EDIT #2: Mass Assignment Link Here

Straight from laravel docs:

The fillable property specifies which attributes should be mass-assignable. This can be set at the class or instance level.

class User extends Eloquent {

    protected $fillable = array('first_name', 'last_name', 'email');

}

EDIT #3:

I'd also suggest not mixing fluent with eloquent models. You've already included the Permission model into your seeder. You should use that instead in case the name of your permissions table changes, so you only need to change the protected $table; attribute inside your model.


An Example straight from Laravel Docs:

// Retrieve the user by the attributes, or create it if it doesn't exist...
$user = User::firstOrCreate(array('name' => 'John'));

Laravel Docs