Created
July 12, 2017 13:59
-
-
Save asvae/6877ed58d1ae72859d54a9174fa40b96 to your computer and use it in GitHub Desktop.
Laravel database fixture example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Upping\Console\Commands; | |
use Bican\Roles\Models\Role; | |
use Illuminate\Console\Command; | |
use Upping\Models\User; | |
use Upping\Repositories\UserRepository; | |
class FixUserRoles extends Command | |
{ | |
/** | |
* The name and signature of the console command. | |
* | |
* @var string | |
*/ | |
protected $signature = 'users:fix-roles'; | |
/** | |
* The console command description. | |
* | |
* @var string | |
*/ | |
protected $description = 'Get roles related stats for all users and try to fix'; | |
/** | |
* @var int | |
*/ | |
private $empty; | |
/** | |
* @var int | |
*/ | |
private $moreThanOne; | |
/** | |
* @var int | |
*/ | |
private $oneRole; | |
/** | |
* @var Role | |
*/ | |
private $defaultRole; | |
public function handle() | |
{ | |
$this->empty = 0; | |
$this->moreThanOne = 0; | |
$this->oneRole = 0; | |
$this->defaultRole = app('user.repository')->getDefaultRole(); | |
User::with('roles')->chunk(100, function ($users) { | |
$users->each(function ($user) { | |
/** @var User $user */ | |
$count = $user->roles->count(); | |
if ($count === 0) { | |
$this->empty++; | |
$role = Role::where('slug', $user->user_type)->first(); | |
$user->attachRole($role); | |
$this->line("Fixed user {$user->id}. Role set to {$role->slug}."); | |
return; | |
} | |
if ($count === 1) { | |
$this->oneRole++; | |
return; | |
} | |
$this->moreThanOne++; | |
}); | |
}); | |
$stats = "Users with" . "\r\n empty roles: " . $this->empty . "\r\n one role: " . $this->oneRole . "\r\n more than one role: " . $this->moreThanOne; | |
$this->info($stats); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment