Skip to content
Advertisement

How to ensure, that column names are equal in laravel?

I am currently working on a laravel php project. In this case, a table containing countries should be created. There are three fields within the table: a short country code column called country_code and the name of the country in german and english language in the columns country_name_de and country_code_en. This results in the following model class:

JavaScript

Further, there is a seeder to write the needed values into the database. The seeder of course needs the column names to insert data. Currently I am using this method within the seeder:

JavaScript

Is it a good style to use ‘constants’/getters to ensure, that there is no typo in any class referencing a specific column of the table? And is it possible to use this style also for the migrations or are there any problems with that?

Advertisement

Answer

Your migration should not be dependent on any Model reference.

Actually if you have $fillable set in your model, using getters would not be needed, because Eloquent will do that for you. To ensure correctness, you can verify that your tables has required columns by:

JavaScript

In a different approach, you can do this:

JavaScript

By this you don’t need those boilerplate method in your model, eloquent will populate respective fields of your model’s table.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement