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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With