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:

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

/**
 * Class Country
 * @package AppModels
 * @mixin IlluminateDatabaseEloquentBuilder
 */
final class Country extends Model
{
    use HasFactory;

    protected $table = 'countries';

    protected $primaryKey = 'country_code';
    protected $keyType = 'string';
    public $incrementing = false;
    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public $fillable = [
        'country_code',
        'country_name_de',
        'country_name_en',
    ];


    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
    ];

    public static function getCountryCodeColumnName(): string
    {
        return 'country_code';
    }

    public static function getGermanCountryNameColumnName(): string
    {
        return 'country_name_de';
    }

    public static function getEnglishCountryNameColumnName(): string
    {
        return 'country_name_en';
    }

    public static function getTableName(): string
    {
        return 'countries';
    }


}

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:

public function run()
{
    // Load CSV-file country_codes.csv
    if (($handle = fopen(storage_path('app/country_codes.csv'), 'r')) !== FALSE) {
        while (($data = fgetcsv($handle)) !== FALSE) {
            $country = array(
                Country::getCountryCodeColumnName()         => $data[0],
                Country::getGermanCountryNameColumnName()   => $data[1],
            Country::getEnglishCountryNameColumnName()  => $data[2],
            );
            Country::create($country);
        }
    }
    fclose($handle);
}

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:

$columns = Schema::getColumnListing('countries'); 
// check if $columns have all your required column

In a different approach, you can do this:

while (($data = fgetcsv($handle)) !== FALSE) {
  $country = new Country();
  $country->setCountryCode = $data[0];
  $country->setCountryNameDe = $data[0];
  $country->setCountryNameEn = $data[1];
  $country->save();
}

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