|
3 | 3 | namespace Rappasoft\LaravelLivewireTables\Commands;
|
4 | 4 |
|
5 | 5 | use Illuminate\Console\Command;
|
| 6 | +use Illuminate\Database\Eloquent\Model; |
6 | 7 | use Illuminate\Support\Facades\File;
|
7 | 8 | use Illuminate\Support\Str;
|
8 | 9 | use Livewire\Commands\ComponentParser;
|
@@ -141,8 +142,8 @@ public function classContents(): string
|
141 | 142 | $template = file_get_contents(__DIR__.DIRECTORY_SEPARATOR.'table-with-model.stub');
|
142 | 143 |
|
143 | 144 | $contents = str_replace(
|
144 |
| - ['[namespace]', '[class]', '[model]', '[model_import]'], |
145 |
| - [$this->parser->classNamespace(), $this->parser->className(), $this->model, $this->getModelImport()], |
| 145 | + ['[namespace]', '[class]', '[model]', '[model_import]', '[columns]'], |
| 146 | + [$this->parser->classNamespace(), $this->parser->className(), $this->model, $this->getModelImport(), $this->generateColumns($this->getModelImport())], |
146 | 147 | $template
|
147 | 148 | );
|
148 | 149 | } else {
|
@@ -204,4 +205,40 @@ public function getModelImport(): string
|
204 | 205 |
|
205 | 206 | return 'App\Models\\' . $this->model;
|
206 | 207 | }
|
| 208 | + |
| 209 | + /** |
| 210 | + * @param string $modelName |
| 211 | + * @return string |
| 212 | + * @throws Exception |
| 213 | + */ |
| 214 | + private function generateColumns(string $modelName): string |
| 215 | + { |
| 216 | + $model = new $modelName(); |
| 217 | + |
| 218 | + if ($model instanceof Model === false) { |
| 219 | + throw new \Exception('Invalid model given.'); |
| 220 | + } |
| 221 | + |
| 222 | + $getFillable = array_merge( |
| 223 | + [$model->getKeyName()], |
| 224 | + $model->getFillable(), |
| 225 | + ['created_at', 'updated_at'] |
| 226 | + ); |
| 227 | + |
| 228 | + $columns = "[\n"; |
| 229 | + |
| 230 | + foreach ($getFillable as $field) { |
| 231 | + if (in_array($field, $model->getHidden())) { |
| 232 | + continue; |
| 233 | + } |
| 234 | + |
| 235 | + $title = Str::of($field)->replace('_', ' ')->ucfirst(); |
| 236 | + |
| 237 | + $columns .= ' Column::make("' . $title . '", "' . $field . '")' . "\n" . ' ->sortable(),' . "\n"; |
| 238 | + } |
| 239 | + |
| 240 | + $columns .= " ]"; |
| 241 | + |
| 242 | + return $columns; |
| 243 | + } |
207 | 244 | }
|
0 commit comments