Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 648
naT erraT Avatar asked Nov 11 '16 09:11

naT erraT


2 Answers

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.

like image 199
Alexey Mezenin Avatar answered Oct 14 '22 05:10

Alexey Mezenin


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.

like image 31
Risan Bagja Pradana Avatar answered Oct 14 '22 06:10

Risan Bagja Pradana