Skip to content

Instantly share code, notes, and snippets.

@devmatheus
Created August 25, 2016 19:50
Show Gist options
  • Save devmatheus/37f134e5f90de6b94714645e4139e01c to your computer and use it in GitHub Desktop.
Save devmatheus/37f134e5f90de6b94714645e4139e01c to your computer and use it in GitHub Desktop.
Generate entity from table - Laravel 5.3
<?php
#path routes/console.php
Artisan::command('entity:generate', function () {
$modelName = $this->ask('Model Name');
$tableName = $this->ask('Table Name');
$fs = new Illuminate\Filesystem\Filesystem();
$pdo = DB::getPdo();
$ds = DIRECTORY_SEPARATOR;
$query = $pdo->prepare('SHOW KEYS FROM ' . $tableName . ' WHERE Key_name = \'PRIMARY\'');
$query->execute();
$primaryKey = $query->fetch()['Column_name'];
$query = $pdo->prepare('DESCRIBE ' . $tableName);
$query->execute();
$tableFields = array_diff(
$query->fetchAll(PDO::FETCH_COLUMN),
[
$primaryKey,
'created_at',
'updated_at'
]
);
$stub = str_replace(
[
'DummyNamespace',
'DummyClass',
'dummyTable',
'dummyPrimary',
'dummyFillable',
'dummyTimestamps'
],
[
'App',
$modelName,
$tableName,
$primaryKey,
'\'' . implode('\',' . PHP_EOL . ' \'', $tableFields) . '\'',
array_search('created_at', $tableFields) !== false ? '':'public $timestamps = false;'
],
$fs->get(base_path('resources' . $ds . 'stubs' . $ds . 'model.stub'))
);
$fs->put(
app_path($modelName . '.php'),
$stub
);
$this->info('Entity created successfully!');
});
<?php
#path resources/stubs/model.stub
namespace DummyNamespace;
use Illuminate\Database\Eloquent\Model;
class DummyClass extends Model
{
protected $table = 'dummyTable';
protected $primaryKey = 'dummyPrimary';
protected $fillable = [
dummyFillable
];
dummyTimestamps
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment