Skip to content

Instantly share code, notes, and snippets.

@ignasbernotas
Last active July 5, 2022 12:53
Show Gist options
  • Save ignasbernotas/5df035ee6d72b43282d844e443886c34 to your computer and use it in GitHub Desktop.
Save ignasbernotas/5df035ee6d72b43282d844e443886c34 to your computer and use it in GitHub Desktop.
A super simple artisan command to generate setting model properties

php artisan set:model YoutubeVideo

$youtubeVideo = new YoutubeVideo();
$youtubeVideo->creator_id = 0;
$youtubeVideo->title = "";
$youtubeVideo->description = "";
$youtubeVideo->thumbnail_url = "";
$youtubeVideo->video_id = "";
$youtubeVideo->is_live = 0;
$youtubeVideo->channel_title = "";
$youtubeVideo->channel_id = "";
$youtubeVideo->playlist_id = "";
$youtubeVideo->view_count = 0;
$youtubeVideo->language = "";
$youtubeVideo->published_at = now();
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class SetModelAttributes extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'set:model {model}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate model object attribute fill';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$name = $this->argument('model');
$model = '\App\Models\\' . Str::camel($name);
$nsModel = new $model();
$table = $nsModel->getTable();
$results = DB::select('SHOW COLUMNS FROM ' . $table);
$var = '$' . Str::camel($name);
$output = $var . ' = new ' . Str::ucfirst($name) . '();' . PHP_EOL;
foreach ($results as $result) {
$defaultValueForType = $this->getDefaultValueForType($result->Field, $result->Type);
if (is_null($defaultValueForType)) {
continue;
}
$output .= $var . '->' . $result->Field
. ' = '
. $defaultValueForType . PHP_EOL;
}
echo $output, PHP_EOL;
return 0;
}
protected function getDefaultValueForType(string $field, string $type)
{
if (in_array($field, ['created_at', 'updated_at'])) {
return null;
}
if (in_array($field, ['id'])) {
return null;
}
if ($type === 'timestamp') {
return 'now();';
}
if (Str::contains($type, ['char', 'var', 'text'])) {
return '"";';
}
if (Str::contains($type, ['int', 'double', 'float'])) {
return '0;';
}
return null;
}
}
@horaciod
Copy link

horaciod commented Jul 5, 2022

using Schema::getColumnListing($table) instead of DB::select('SHOW COLUMNS FROM ' . $table) allow to access to columns in other databases like postgresql
thanks anyway, super handy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment