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?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community