mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
https://www.mongodb.com/compatibility/mongodb-laravel-integration
MIT License
6.99k stars 1.42k forks source link

Model::getAttribute() doesn't work when a method has the same name as attribute #1156

Open ng1091 opened 7 years ago

ng1091 commented 7 years ago

I created a Model like this:

class Article extends Moloquent
{
    // this class has an attribute like
    protected $fillable = ['like'];

    // and a static method like
    public static function like($article_id, $user_id) {
        // ...
        $article = static::find($article_id);
        $article->increment('like'); // here doesn't work
    }
}

Jenssegers\Mongodb\Eloquent\Model; line 125:

    public function getAttribute($key)
    {
        if (! $key) {
            return;
        }

        // Dot notation support.
        if (str_contains($key, '.') and array_has($this->attributes, $key)) {
            return $this->getAttributeValue($key);
        }

        // This checks for embedded relation support.
        if (method_exists($this, $key) and ! method_exists(self::class, $key)) {
            return $this->getRelationValue($key);
        }

        return parent::getAttribute($key);
    }

The problem is method_exists($this, $key) returns true and try to getRelationValue(), but Article::like() is a static method, so it will crash.

GromNaN commented 1 year ago

Should be fixed by #2577