Created
August 25, 2016 19:50
-
-
Save devmatheus/37f134e5f90de6b94714645e4139e01c to your computer and use it in GitHub Desktop.
Generate entity from table - Laravel 5.3
This file contains hidden or 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 | |
#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!'); | |
}); |
This file contains hidden or 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 | |
#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