Limit the Insert of Records in Laravel
current what i want to achieve is i want to limit the records to suppose a 100 now when ever we try to insert a new record we should delete the one (first) record and insert the newly created one
currently iam doing manually like this
if(Logs::count() >= 100){ Logs::fist()->delete(); //fuction call again }
else{ Logs::create(); }
i want to simply this and trying to make in centralised
CodePudding user response:
yes i after some researh i find solution i have used model observer
protected static function boot()
{
parent::boot();
static::created(function ($model) {
/* Getting the log limt */
$setting = Setting::where(['option' => 'log_queue_size'])->first();
if ($setting) {
$limit = $setting->value['log_queue_size'] ?? 100;
$logQuery = Log::get();
$keepIds = $logQuery->take($limit)->pluck('id');
Log::whereNotIn('id', $keepIds)->delete();
}
});
}
CodePudding user response:
You don't need to get all the records from DB you just need the count of records
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::created(function ($model) {
/* Getting the log limt */
$setting = Setting::where(['option' => 'log_queue_size'])->first();
if ($setting) {
$limit = $setting->value['log_queue_size'] ?? 100;
$actualCount = Log::query()->count();
if ($actualCount > $limit) {
$recordsToDelete = $actualCount - $limit;
Log::query()->latest()->take($recordsToDelete)->delete();
}
}
});
}