How to display all session info stored in database (Laravel)

Viewed 3790

Is there anyway to display all sessions data ?

I tried this way

 Session::all();

but it return current user info not all stored sessions

Then I tried this code

DB::table('sessions')->get();

it retrieve all stored data but everything is encrypted like this

  [id] => zZLNtqmennbg3gdsfdsffdstlvdZfjKtzZTP7Or6Tk
  [user_id] => 
  [ip_address] => 196.144.136.233
  [user_agent] => Mozilla/5.0 (Linux; Android 7.0; SM-G610F Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.91 Mobile Safari/537.36
  [payload] => YTozOntzOjY6Il90b2tlbiI7czo0MDoiOVJXSmdkZlFnVktNU3lVVlBQSFdKOElrRFFMVEdtYUJnMENiQzY4NSI7czo5OiJfcHJldmldfdsfdsfdfzOiJ1cmwiO3M6MzM6Imh0dHBzOi8vYXJldmlld3NhcHAuY29tL2Vycm9yXzQwNCI7fXM6NjoiX2ZsYXNoIjthOjI6e3M6Mzoib2xkIjthOjA6e31zOjM6Im5ldyI7YTowOnt9fX0=
  [last_activity] => 1535513730

Also I don't have user_id since I use custom sessions

This code returns the correct data but for one user only

 Session::all();

How can I retrieve all sessions data like this ?

  ["plan_type"]=> string(7) "test" ["shop"]=> string(36) "test.test.com"  

Because what stored in database is encrypted I want user data so I know how many session each user have

1 Answers

Just make your own model and reference the same table

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class CustomSession extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'sessions';
}

Use it as any other model... CustomSession::all();

As for the decryption, you can do it like this: https://laracasts.com/discuss/channels/laravel/accessing-the-session-payload-as-a-json-object

$payload = unserialize(base64_decode($session->payload)); // At this point you have an array

Of course you would have to do it on for and then you can assign it like

   foreach($sessions as $session){
       $session->payload = unserialize(base64_decode($session->payload));
   }

And as the comments in the link say:

// If you want an object instead, you could typecast it to a stdObject.
// $payload = (object) unserialize(base64_decode($session->payload));

So then you can use it as

$session->payload->someSome;
Related