Home > OS >  Eloquent formatting data with __get
Eloquent formatting data with __get

Time:05-17

I'm quite new to PHP / Eloquent in general and I'm trying to make a little data formatter in my Model class.

public function __get($key)
{
    switch ($key) {
        case "preferred":
            $this->attributes[$key . "_formatted"] = ($this->getAttribute($key) == 1) ? "Yes" : "No";
            break;
    }

    return parent::__get($key);
}

which works fine, it formats the data I want it to format. Thought when I want to $model->update() I get the error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'preferred_formatted' in 'field list' 

Is there a way so I can make it so when I update my $model it doesn't look for preferred_formatted. I've tried making it hidden but to no avail, I've also tried some different solutions but at this point I'm not sure if there's a better way to format data or if I'm doing something wrong, any help is appreciated.

CodePudding user response:

Just add a new attribute to your model:

class MyModel{
    public function getPreferredFormattedAttribute()
    {
        ($this->preferred == 1) ? $formatted = 'Yes' : 'No';
        return $formatted;
    }
}

Then you can call the MyModel attribute like this:

$myModel = MyModel->find(1);
$myModel->preferred_formatted;
// or
$myModel->PreferredFormatted;

CodePudding user response:

Another way is to use global helper: Create a file /app/helper/myHelper.php and add it to composer.json

"autoload": {
     "files": [
         "app/helper/myHelper.php"
     ]
 },

put your code there:

<?php

if(!function_exists('formatYesNo')){
    function formatYesNo($valueToBeFormatted)
    {
        (valueToBeFormatted == 1) ? $formatted = 'Yes' : 'No';
        return $formatted;
    }
}

Use it anyware as:

$myModel = MyModel->find(1);
formatYesNo($myModel->preferred);
  • Related