Reputation: 541
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
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
Reputation: 163768
What you can do:
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
Use Global Scope.
Create trait and use it in all or some of your models.
Upvotes: 13