Answer the question
In order to leave comments, you need to log in
How to change field which is checked in laravel condition?
Good afternoon. Such a problem. I check active users, and if it has not been updated for more than three months, I want to make it archived, changing active to 0. I made such a condition with the method. I check by running the seeder.
$users = User::where('active', 1)->whereDate('updated_at', '<=', date('Y-m-d H:i:s', strtotime('-90 days')))->get();
if (!empty($users)) {
foreach ($users as $user) {
if (!empty($user)) {
if ($user->active == 1) {
$user->active = 0;
$user->save();
}
}
}
}
Answer the question
In order to leave comments, you need to log in
\DB::table('users')
->where('active', true)
->whereDate('updated_at', '<=', now()->subMonths(3))
->update(['active' => false]);
Why do you need active in principle? Why can't you just use updated_at in the selections where you need it? Judging by the fact that you are asking this question, there is no reason.
Before debugging, you should first refactor the code) to reduce cyclomatic complexity and increase readability:
$lastActiveDate = date('Y-m-d H:i:s', strtotime('-90 days'));
$users = User::where('active', 1)
->whereDate('updated_at', '<=', $lastActiveDate)
->get();
if ($users->isEmpty()) {
return;
}
foreach ($users as $user) {
if ($user->isEmpty()) {
continue;
}
if ($user->active == 1) {
$user->active = 0;
$user->save();
}
}
foreach ($users as $user) {
$user->active = 0;
$user->save();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question