在Laravel 5.2中为所有Eloquent模型添加全局方法


Add global method to all Eloquent Models in Laravel 5.2

我想添加给定的方法到我所有的雄辩模型:

public function isNew(){
    return $this->created_at->addWeek()->gt(Carbon::now());
}

这可能不使用暴力吗?

I could not find anything in the docs

谢谢

你能做的:

  1. 创建BaseModel类,并将所有类似的方法放入其中。然后将BaseModel类扩展到所有型号,而不是Model类:

class Profile extends BaseModel

  • 使用全局作用域

  • 创建trait并在所有或部分模型中使用。

    当然可以。只需简单地扩展Laravel的雄辩模型,如下所示:

    use Carbon'Carbon;
    use Illuminate'Database'Eloquent'Model;
    abstract class BaseModel extends Model
    {
        public function isNew() {
            return $this->created_at->copy()->addWeek()->gt(Carbon::now());
        }
    }
    

    现在你的模型应该从这个新的BaseModel类扩展:

    class User extends BaseModel {
        //
    }
    

    你可以这样做:

    User::find(1)->isNew()
    

    注意,我还在created_at属性上调用copy()方法。这样,你的created_at属性将被复制,而不会在1周前意外添加。

    // Copy an instance of created_at and add 1 week ahead.
    $this->created_at->copy()->addWeek()