2

Suppose there is a Website model like this :

class Website extends Authenticatable
{
        protected $primaryKey = 'website_id';

        public function deposits ()
        {
            return $this->hasMany(\App\AdminDeposit::class, 'website', 'website_id');
        }

}

And in the other hand there is a AdminDepoist Model like this:

class AdminDeposit extends Model
    {
        protected $primaryKey = 'deposit_id';

        public function website ()
        {
            return $this->belongsTo(\App\Website::class, 'website', 'website_id');
        }

    }

As you can see there is one to many relationship between them where each website can have some deposits.

AdminDeposit model has a created_at attribute that setted each time a new deposit inserted.

Now I want to select websites that is left less than 5 days from last their deposits. (means if(website->last_deposit <= 5 days))

then I want to select websites that their last deposit between 5 and 10 days.

and finally those that their last deposit is greater than 30 days.

I know that should be used whereHas() along with Carbon library but I do not know how?

Ahmad Badpey
  • 6,348
  • 16
  • 93
  • 159

1 Answers1

2

Create a new hasOne relationship to get one latest deposit:

public function latestDeposit()
{
    return $this->hasOne(AdminDeposit::class, 'website', 'website_id')->latest();
}

Websites that is left less than 5 days from last their deposit

Website::whereHas('latestDeposit', function($q) {
    $q->where('created_at', '>', now()->subDays(5));
})->get();

Websites that their last deposit between 5 and 10 days.

Website::whereHas('latestDeposit', function($q) {
    $q->whereBetween('created_at', [now()->subDays(10), now()->subDays(5)]);
})->get();

Those that their last deposit is greater than 30 days

Website::whereHas('latestDeposit', function($q) {
    $q->where('created_at', '<', now()->subDays(30));
})->get();
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279