I
I
Ivan2020-07-31 17:24:48
Laravel
Ivan, 2020-07-31 17:24:48

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();
                    }
                }
            }
        }

When starting this seeder, if the condition is met, it loops, or something else. It hangs shorter, Ctrl+C helps. Thus it all the same updates the first suitable record in the table. If you try to change another field, not active, everything works as intended. I tried without all these ifs, only forich, the same thing. What's wrong and how to fix it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
jazzus, 2020-07-31
@Djonson86

\DB::table('users')
   ->where('active', true)
   ->whereDate('updated_at', '<=', now()->subMonths(3))
   ->update(['active' => false]);

A
Alex Wells, 2020-08-01
@Alex_Wells

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.

D
Daria Motorina, 2020-07-31
@glaphire

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();
    }  
}

I don't remember exactly, but the normal empty function won't work on the $users collection, on $user in the foreword maybe
UPD. In fact, users with is_active=1 are already selected in the request, so the forych can be reduced to:
foreach ($users as $user) {
    $user->active = 0;
    $user->save();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question