Skip to content

Commit

Permalink
auto generating columns from model fillable
Browse files Browse the repository at this point in the history
  • Loading branch information
Wiz-Amit committed Jan 9, 2022
1 parent 5ec4a23 commit 4c681b1
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
41 changes: 39 additions & 2 deletions src/Commands/MakeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Livewire\Commands\ComponentParser;
use Illuminate\Database\Eloquent\Model;
use Livewire\Commands\MakeCommand as LivewireMakeCommand;

/**
Expand Down Expand Up @@ -141,8 +142,8 @@ public function classContents(): string
$template = file_get_contents(__DIR__.DIRECTORY_SEPARATOR.'table-with-model.stub');

$contents = str_replace(
['[namespace]', '[class]', '[model]', '[model_import]'],
[$this->parser->classNamespace(), $this->parser->className(), $this->model, $this->getModelImport()],
['[namespace]', '[class]', '[model]', '[model_import]', '[columns]'],
[$this->parser->classNamespace(), $this->parser->className(), $this->model, $this->getModelImport(), $this->generateColumns($this->getModelImport())],
$template
);
} else {
Expand Down Expand Up @@ -204,4 +205,40 @@ public function getModelImport(): string

return 'App\Models\\' . $this->model;
}

/**
* @param string $modelName
* @return string
* @throws Exception
*/
private function generateColumns(string $modelName): string
{
$model = new $modelName();

if ($model instanceof Model === false) {
throw new \Exception('Invalid model given.');
}

$getFillable = array_merge(
[$model->getKeyName()],
$model->getFillable(),
['created_at', 'updated_at']
);

$columns = "[\n";

foreach ($getFillable as $field) {
if (in_array($field, $model->getHidden())) {
continue;
}

$title = Str::of($field)->replace('_', ' ')->ucfirst();

$columns .= ' Column::make("' . $title . '", "' . $field . '")' . "\n" . ' ->sortable(),' . "\n\n";
}

$columns .= " ]\n";

return $columns;
}
}
4 changes: 1 addition & 3 deletions src/Commands/table-with-model.stub
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ class [class] extends DataTableComponent

public function columns(): array
{
return [
Column::make('Column Name'),
];
return [columns];
}

public function query(): Builder
Expand Down

0 comments on commit 4c681b1

Please sign in to comment.