Tarre Tan Tarre Tan - 1 year ago 77
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


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download