xtremeCODE
xtremeCODE

Reputation: 719

How to get user's sessions when using the database session driver?

I want to check the logged-in user and the user_id column in Session table and also count the result. So I tried to use this

    $login = Session::where('user_id', Auth::id())->count();

But it returned this error

Call to undefined method Illuminate\Session\Store::where()

Upvotes: 0

Views: 38

Answers (1)

Hafez Divandari
Hafez Divandari

Reputation: 9069

You have 2 options:

  1. Use DB facade:

    use Illuminate\Support\Facades\DB;
    
    $login = DB::table('sessions')->where('user_id', Auth::id())->count();
    
  2. define a new Session model and use it to count logins:

    • php artisan make:model Session

      $login = \App\Session::where('user_id', Auth::id())->count();
      
    • By this way, you can also define a sessions relationship on user model:

      class User extends Authenticatable
      {
          /**
           * Get the sessions of the user.
           */
          public function sessions()
          {
              return $this->hasMany('App\Session');
          }
      }
      

      and call it like this:

      $login = Auth::user()->sessions()->count();
      

Upvotes: 1

Related Questions