Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vlauciani's avatar

Using one "Accessor" in more then one Model

Hi all

I need to execute a simple PHP 'round' function on Latitude and Longitude attributes that are stored in differente MySQL tables.

Now I've two methods:

class Restaurant extends Model {
    public function getLonAttribute($value)
    {
        return round($value, 3);
    }
    
    public function getLatAttribute($value)
    {
        return round($value, 3);
    }
}

and

class Bar extends Model {
    public function getLonAttribute($value)
    {
        return round($value, 3);
    }
    
    public function getLatAttribute($value)
    {
        return round($value, 3);
    }
}

I don't want to repeat these functions for each Model where I need to 'round' the Latitude and Longitude; what is the best practice to write It one time and inherited these functions into the Models?

0 likes
6 replies
sebdd's avatar

I'd put them in a trait.

trait HasLocationAttributes {
    public function getLonAttribute($value)
    {
        return round($value, 3);
    }
    
    public function getLatAttribute($value)
    {
        return round($value, 3);
    }
}

class Restaurant extends Model {
    use HasLocationAttributes;
}

class Bar extends Model {
    use HasLocationAttributes;
}
1 like
vlauciani's avatar

Thank you @sebdd But, where I can find a guide/example for "trait"? I've never used it and I don't know If I need create (and where) a file for "trait" functions; is this a new Model file? Thank you again.

vlauciani's avatar

Thank you @JarekTkaczyk for the link.

The concept is clear, but I need to understand how to implements in Laravel5. The "trait" code should be written into which folder? how I can the file?

Thank you.

xingfucoder's avatar

Hi @vlauciani if you are using any Domain Layer composed of some folders, you could make a Core folder to put some of those traits, interfaces or classes that you may reuse.

Please or to participate in this conversation.