将全局方法添加到Laravel 5.2中的所有Eloquent模型

时间:2016-11-11 09:50:57

标签: php laravel eloquent laravel-5.2

我想为所有我的Eloquent模型添加给定的方法:

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

这可以不用暴力吗?

我在文档中找不到任何内容

由于

2 个答案:

答案 0 :(得分:7)

你能做什么:

  1. 创建BaseModel类并将所有类似的方法放入其中。然后在所有模型中扩展此BaseModel类,而不是Model类:
  2. class Profile extends BaseModel

    1. 使用Global Scope

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

答案 1 :(得分:3)

当然,你可以做到。只需简单地扩展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()

请注意,我还在copy()属性上调用created_at方法。这样,您的created_at属性就会被复制,并且不会在一周内意外添加。

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

希望得到这个帮助。