naT erraT
naT erraT

Reputation: 541

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

Upvotes: 7

Views: 2735

Answers (2)

Risan Bagja Pradana
Risan Bagja Pradana

Reputation: 4674

Sure, you can do that. Just simply extend the Laravel's eloquent model like so:

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());
    }
}

Now your model should extend from this new BaseModel class instead:

class User extends BaseModel {
    //
}

This way you can do something like this:

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

Note that I also call copy() method on the created_at property. This way your created_at property would be copied and won't be accidentally added 1 week ahead.

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

Hope this help.

Upvotes: 4

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

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.

Upvotes: 13

Related Questions