CasperSecurity
<?php
namespace Database\Seeders;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
class LaratrustSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->truncateLaratrustTables();
$roles = [
'superadmin',
'admin',
'hr',
'employee'
];
// Create roles and assign them IDs
$roleIds = [];
foreach ($roles as $roleName) {
$role = \App\Models\Role::firstOrCreate([
'name' => $roleName,
'display_name' => ucwords($roleName),
'description' => ucwords($roleName),
]);
$roleIds[$roleName] = $role->id;
$this->command->info("Role '{$roleName}' created with ID: {$role->id}");
}
if (Config::get('laratrust_seeder.create_users')) {
$this->command->info('Creating default users with role IDs');
// Create users and assign role IDs
$users = [
[
'name' => 'Superadmin',
'email' => 'superadmin@yobytech.in',
'password' => bcrypt('Password@1'),
'role_id' => $roleIds['superadmin'], // Assigning the role_id directly
'role_name' => 'Superadmin', // Explicitly set the role_name
],
[
'name' => 'Admin',
'email' => 'admin@yobytech.in',
'password' => bcrypt('Password@1'),
'role_id' => $roleIds['admin'], // Assigning the role_id directly
'role_name' => 'Admin', // Explicitly set the role_name
],
];
foreach ($users as $userData) {
$user = \App\Models\User::create($userData);
// Attach the role using Laratrust
$user->attachRole($userData['role_id']);
$this->command->info("User '{$userData['name']}' created with role ID: {$userData['role_id']}");
}
}
}
/**
* Truncates all the laratrust tables and the users table
*
* @return void
*/
public function truncateLaratrustTables()
{
$this->command->info('Truncating User, Role, and Permission tables');
Schema::disableForeignKeyConstraints();
DB::table('permission_role')->truncate();
DB::table('permission_user')->truncate();
DB::table('role_user')->truncate();
if (Config::get('laratrust_seeder.truncate_tables')) {
DB::table('roles')->truncate();
DB::table('permissions')->truncate();
if (Config::get('laratrust_seeder.create_users')) {
$usersTable = (new \App\Models\User)->getTable();
DB::table($usersTable)->truncate();
}
}
Schema::enableForeignKeyConstraints();
}
}