Skip to content

Instantly share code, notes, and snippets.

@localdisk
Created July 20, 2016 13:34
Show Gist options
  • Save localdisk/11c9371e9b9367830ef4cbfdea2de81d to your computer and use it in GitHub Desktop.
Save localdisk/11c9371e9b9367830ef4cbfdea2de81d to your computer and use it in GitHub Desktop.
Postを作るコマンド
<?php
namespace App\Console\Commands;
use App\Post;
use Carbon\Carbon;
use Faker\Factory;
use Illuminate\Console\Command;
class MakePost extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:post {count=100}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Seeding Post.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// パラメータ取得
$count = (int)$this->argument('count');
// テーブルを truncate
Post::truncate();
// インサート処理
$loop = (int)floor($count / 100);
$remainder = $count % 100;
// プログレスバー
$bar = $this->output->createProgressBar($loop + 1);
for ($i = 0; $i < $loop; $i++) {
$users = $this->times(100);
// 100 ずつ bulk insert
Post::insert($users);
$bar->advance();
}
// 余りをインサート
Post::insert($this->times($remainder));
$bar->advance();
$bar->finish();
$this->info("done.");
}
protected function times($count)
{
$faker = Factory::create();
$now = Carbon::now();
$attributes = [];
for ($i = 0; $i < $count; $i++) {
$attributes[] = [
'title' => $faker->title,
'body' => $faker->sentence,
'updated_at' => $now,
'created_at' => $now,
];
}
return $attributes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment