Support the ongoing development of Laravel.io →
Eloquent Forms Architecture

In Laravel, I have a tiny yet annoying problem changing many files when I decide to change a database field (due to fuzzy requirements). When I change a db field, first I have to change it in migrations, then the model (attribute names and validators), then my seeder, and later my forms. For me its kind of a hassle. I thought of a solution: I could have a public $fields in my model that could contain the name of my field, and type, then simply use this array to dynamically create fields in my migrations folder. This way I can call $fields anywhere I needed to. It could be like:

// in Mymodel.php
class Mymodel extends Model
{
  public $fields = [
    ['name'=>'id','type'=>'increments'],
    ['name'=>'sometextfield', type=>'text'],
  ];
}

Then in my up( ) function of my migration (inside Schema::create) I could do like so:

foreach(Mymodel::$fields as $field)
{
    $table->{$field['type']}($field['name']);
}

Of course this current example won't work for other cases, and that can be fixed. But is this a good practice to stop being repetitive in editing and just define everything like this in my model? Or is there a better approach?

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

JamesA1 jamesa1 Joined 31 Jul 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.