Adding Setters and Getters to Laravel Model

Stefan Izdrail

Founder & Senior Architect · 2026-06-29

Laravel Company
Title: Adding Setters and Getters to Laravel Model for Interface Implementation Compliance Introduction: In the world of object-oriented programming, interfaces are crucial as they provide a contract between classes that define what methods must be implemented by their implementing classes. In Laravel, Eloquent models leverage this concept through the use of various magic methods, which allow you to define custom setters and getters without necessarily writing them explicitly. We can extend model classes with interfaces to adhere to these contracts - but how do we add setters and getters for these specific interface implementations? This blog post will guide you on a Laravel-friendly approach to this problem. The Approach: To address the issue of adding custom setters and getters in an Eloquent Model while implementing an interface, you can take advantage of Laravel's magic methods. Magic methods are a feature of PHP that allows classes to define their behavior dynamically by calling specific methods when using certain keywords such as __construct() or __get(). In this case, you can leverage the following magic methods: - __set(): This method is called whenever you try to assign a new value to a property. The first argument represents the name of the property being set. - __get(): This method is invoked when you attempt to access (or get) the value of a property. Similar to __set(), it accepts one argument that represents the name of the property in question. Your Code: Using these magic methods, you can modify your existing code to comply with an interface while maintaining Laravel's conventions as follows:
class MyClass extends Model implements someContract
{
  private $foo; // Define a protected property for the interface implementation

  public function getFoo() {
    return $this->foo;
  }

  // Add this method to define your custom setter in Laravel's way
  public function setFoo($value) {
      $this->foo = $value;
      return $this;
  }
}
Explanation: In the code above, we have moved the setter logic outside of the `MyClass` class and replaced it with a simpler approach that follows Laravel's conventions. We defined a protected property named `$foo`, which will hold the value assigned to it through the new setter method. This way, you maintain your interface implementation while keeping things clean and organized. Conclusion: In summary, Laravel provides a simple solution for implementing interfaces on Eloquent Models by leveraging its magic methods. Using the techniques outlined above, you can add custom setters and getters as needed without compromising the integrity of your interface implementation or Laravel's conventions. Always remember to keep your code organized, well-documented, and efficient for future maintenance and collaboration with other developers.