Skip to content

Instantly share code, notes, and snippets.

@vinicius73
Last active August 29, 2015 14:22
Show Gist options
  • Save vinicius73/731b090d82bb7c1893c2 to your computer and use it in GitHub Desktop.
Save vinicius73/731b090d82bb7c1893c2 to your computer and use it in GitHub Desktop.
UserTableSeeder.php com Defender e Faker
<?php
use App\User;
use Artesaos\Defender\Role;
use Illuminate\Database\Seeder;
use Faker\Factory as FactoryFaker;
class UserTableSeeder extends Seeder
{
/**
* @var \Illuminate\Database\Eloquent\Collection
*/
private $roles;
/**
* @var \Faker\Generator
*/
private $faker;
public function run()
{
// Apaga toda a tabela de usuários
DB::table('users')->truncate();
$this->roles = Role::all();
$this->faker = FactoryFaker::create('pt_BR');
// Cria usuários admins (dados controlados)
$this->createAdmins();
// Cria usuários demo dados faker
$this->createUsers();
}
private function createAdmins()
{
$superuserRole = $this->roles->where('name', 'superuser')->first();
$user = User::create([
'email' => '[email protected]',
'name' => 'Vinicius Reis',
'password' => bcrypt('s&nh@')
]);
// attach role to user
$user->attachRole($superuserRole);
$this->command->info('User [email protected] created');
$user = User::create([
'email' => '[email protected]',
'name' => 'João Bobo',
'password' => bcrypt('s&nh@')
]);
$user->attachRole($superuserRole);
$this->command->info('User [email protected] created');
}
private function createUsers()
{
$max = $this->faker->numberBetween(20, 40);
$rolesCount = $this->roles->count();
for($i=0; $i < $max; $i++):
$user = $this->createUser();
// attach random roles to user
$this->attachRoles($user, $rolesCount);
endfor;
$this->command->info($max . ' demo users created');
}
private function createUser()
{
return User::create([
'email' => $this->faker->email,
'name' => $this->faker->name,
'password' => bcrypt(str_random(6))
]);
}
private function attachRoles(User $user, $rolesCount)
{
$number = $this->faker->numberBetween(0, $rolesCount);
if($number > 0):
$roles = collect($this->roles->random($number))->lists('id')->toArray();
$user->roles()->sync($roles);
endif;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment