简体   繁体   中英

Laravel query builder get records for user on log in

I've got a Laravel API and have a function that runs when a user logs in, when they log in, I want to find associated domains linked to their account and get domains based on whether a notification has gone out for domain expiry or SSL expiry.

My code is working, but what I've noticed, is it's finding ALL domains regardless of the user ID, and I just want to get the domains for the user that logged in...

What am I doing wrong here?

/**
 * Log In (log a user into the application)
 *
 * @param  Request  $request
 * @return Response
 */
public function login(Request $request)
{

    // update the last login at time
    try {

      $user = User::findOrFail(Auth::id());
      $user->last_login_at = Carbon::now()->toDateTimeString();
      $this->resetExpiryAlerts($user, Auth::id());
      $user->save();

    } catch (\Exception $e) { }

    // success
    return $this->respondWithToken($token);
}

/**
 * Reset expiry alerts
 *
 */
public function resetExpiryAlerts($user, $id)
{

  $domains = Domains::where('user_id', $id)
                    ->where('domain_last_notified_at', '!=', null)
                    ->orWhere('ssl_last_notified_at', '!=', null)
                    ->get();

  if (count($domains) > 0) {
    foreach ($domains as $key => $domain) {

      if (
        isset($domain->domain_last_notified_at) &&
        ($user->last_login_at >= $domain->domain_last_notified_at)
      ) {
        $domain->domain_last_notified_at = null;
      }

      if (
        isset($domain->ssl_last_notified_at) &&
        ($user->last_login_at >= $domain->ssl_last_notified_at)
      ) {
        $domain->ssl_last_notified_at = null;
      }

      $domain->save();
    }
  }

}

I've removed some irrelevant code from my example, but I think I'm doing something wrong with the query...

$domains = Domains::where('user_id', $id)
                  ->where('domain_last_notified_at', '!=', null)
                  ->orWhere('ssl_last_notified_at', '!=', null)
                  ->get();

Because it appears to be returning any domain regardless of the user ID.

I think the problem is in your query. The last two wheres should be grouped. Try the following:

Domains::where('user_id', $id)
       ->where(function ($query) {
           $query->whereNotNull('domain_last_notified_at')
                 ->orWhereNotNull('ssl_last_notified_at');
       })
       ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM