Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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