Skip to content

Instantly share code, notes, and snippets.

@leogopal
Created December 28, 2018 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leogopal/7ef077bc8768dbdf8406e28a3e9db735 to your computer and use it in GitHub Desktop.
Save leogopal/7ef077bc8768dbdf8406e28a3e9db735 to your computer and use it in GitHub Desktop.

Problem

I have some data that I have in a config file or array that I need to make sure all of that data is in laravel. This is how I accomplish it using firstOfCreate(). In my problem I had a config file with arrays of roles, data types, and permissions, and the latter needed to be merged but it should not create it if it already exists.

<?php
use Illuminate\Database\Seeder;
/**
* Class LocationTableSeeder.
*/
class PermissionTableSeeder extends Seeder
{
use DisableForeignKeys;
/**
* Run the database seed.
*
* @return void
*/
public function run()
{
$this->disableForeignKeys();
// Create the missing Roles
foreach(config('access.user-roles') as $role) {
Role::firstOrCreate(
[ 'name' => $role ]
);
}
// Create the the combined permissions.
foreach (config('access.permissions.model') as $model) {
foreach (config('access.permissions.types') as $type) {
Permission::firstOrCreate(
[ 'name' => strtolower($type) . '-' . strtolower($model) ]
);
}
}
$this->enableForeignKeys();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment