Tarre Tan Tarre Tan - 25 days ago 11
PHP Question

Add global method to all Eloquent Models in Laravel 5.2

I want add given method to all my Eloquent Models:

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


Is this possible to do without bruteforce?

I could not find anything in the docs

Thanks

Answer

What you can do:

  1. Create BaseModel class and put all similar methods in it. Then extend this BaseModel class in all models instead of Model class:

class Profile extends BaseModel

  1. Use Global Scope.

  2. Create trait and use it in all or some of your models.