laravel

【Laravel】DBのカラム情報から$fillableを作るartisanコマンド

More than 1 year has passed since last update.

モデルの$fillable書くのめんどくさいなぁと思ってまして、DBのカラムから作成できるやつを書いてみました。

まずコマンド作成して

$ artisan make:command Fillable

Kernelの登録もしちゃって

app/Console/Kernel.php
    protected $commands = [
        Commands\Fillable::class,
    ];

実装〜

app/Console/Commands/Fillable.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class Fillable extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fillable {table} {--all}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Print fillable from migration file for model.';

    private $exceptions = [
        'id',
        'created_at',
        'updated_at',
        'deleted_at',
    ];

    /**
     * Create a new command instance.
     *
     * @return mixed
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $table = $this->argument('table');

        $columns = collect(DB::select("show columns from $table;"))->pluck('Field');
        $this->info('protected $fillable = [');
        foreach ($columns as $column) {
            if ( $this->option('all') || !in_array($column, $this->exceptions)) {
                $this->info("    '" . $column . "',");
            }
        }
        $this->info('];');
    }
}

試してみる

$ php artisan fillable users
protected $fillable = [
    'name',
    'email',
    'password',
    'remember_token',
];

idとかcreate_atとかも出したいなら--allもつける

$ php artisan fillable users --all
protected $fillable = [
    'id',
    'name',
    'email',
    'password',
    'remember_token',
    'created_at',
    'updated_at',
    'deleted_at',
];

このやり方だと、毎回、Laravelプロジェクトが立ち上がるごとに作んないといけないので、database/migrationsを読むcliを作りたい(いつか)