To handle the transformation of database field names to more readable attribute names in Laravel, you can use Eloquent's getAttribute and setAttribute methods. This allows you to define a mapping array in your model and then use these methods to translate between the database field names and the attribute names you want to use in your application.
Here's how you can achieve this:
- Define a mapping array in your model.
- Override the
getAttributeandsetAttributemethods to handle the translation.
Here's an example implementation:
class MyModel extends \Illuminate\Database\Eloquent\Model
{
protected $table = 'your_table_name';
protected $mapping = [
'ARTICLE_-_SUPPLIER_AID' => 'supplier_aid',
'otherstrangefield' => 'newname',
// Add more mappings as needed
];
public function getAttribute($key)
{
$key = array_search($key, $this->mapping) ?: $key;
return parent::getAttribute($key);
}
public function setAttribute($key, $value)
{
$key = $this->mapping[$key] ?? $key;
return parent::setAttribute($key, $value);
}
}
Explanation:
-
Mapping Array: The
$mappingarray holds the mapping between the database field names and the attribute names you want to use in your application. -
getAttribute Method: This method is overridden to check if the requested attribute name exists in the mapping array. If it does, it translates the attribute name to the corresponding database field name before calling the parent
getAttributemethod. -
setAttribute Method: This method is overridden to check if the attribute name being set exists in the mapping array. If it does, it translates the attribute name to the corresponding database field name before calling the parent
setAttributemethod.
With this setup, you can now use the more readable attribute names in your application code:
$model = MyModel::find(1);
echo $model->supplier_aid; // Accesses ARTICLE_-_SUPPLIER_AID in the database
$model->newname = 'Some Value'; // Sets the value of otherstrangefield in the database
This approach keeps your application code clean and readable while still working with the legacy database field names.