[FIXED] Laravel query builder get records for user on log in

Issue

I have a Laravel API and I have a function that runs when a user logs in. When a user logs in, I would like to find the associated domain linked to their account and retrieve the domain based on whether the domain notification was sent or not. Expiration date or SSL expiration date.

My code works, but I noticed that it searches all domains regardless of the user ID. I just want to get the domain of the logged in user…

What am I doing wrong?

/**
 * Login (logs the user into the application)
 *
 * @param request $request
 * @return response
 */
public function login(Request $request)
{

    // update last login 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
    Returns $this->respondWithToken($token);
}

/**
 * Reset expiration 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 extraneous code from my example, but I think you’re doing something wrong with your query…

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

Because it seems to return any domain regardless of the user ID.

Solution

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

Answered By – IGP

Answer Checked By – Marilyn (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published