Mastering Laravel Magic Methods

In Laravel, magic methods can be used to simplify certain operations, such as accessing model attributes or calling model methods. Here are some commonly used magic methods and their usage:

  1. $get($key): Used to access the model’s properties, this method will be automatically called when trying to access a non-existent property.
// 在模型中使用__get方法
public function __get($key) {
    if ($key === 'full_name') {
        return $this->first_name . ' ' . $this->last_name;
    }
    
    return parent::__get($key);
}
  1. __set($key, $value): Used to set the properties of the model. This method will be automatically called when trying to set a property that does not exist.
// 在模型中使用__set方法
public function __set($key, $value) {
    if ($key === 'full_name') {
        $parts = explode(' ', $value);
        $this->first_name = $parts[0];
        $this->last_name = $parts[1];
    } else {
        parent::__set($key, $value);
    }
}
  1. When a method that does not exist in the model is called, this function will be automatically called.
// 在模型中使用__call方法
public function __call($method, $parameters) {
    if ($method === 'deletePhoto') {
        $this->photo = null;
        $this->save();
    }
}

These magic methods can help simplify code, improve development efficiency, and are widely used in scenarios such as models in Laravel.

bannerAds