Im trying get online users from sessions table. To do this, first I added user_id column to sessions table, then I trying update this user_id whenever the page is refreshed. Here is the Online.php model where scopeUpdateCurrent() function check the user and update user_id in sessions table:
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Session;
use Auth;
class Online extends Model
{
public $table = 'sessions';
public $timestamps = false;
public function user()
{
return $this->belongsTo('App\User');
}
...
public function scopeUpdateCurrent(Builder $query)
{
$user = auth()->user(); // returns null but user logged in
// $user = Auth::user(); // returns null too
return $query->where('id', Session::getId())->update([
'user_id' => $user ? $user->id : null
]);
}
}
Here is the AppServiceProvider.php where I call that updating:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Online;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Online::updateCurrent();
...
}
...
}
The problem is that auth()->user() or Auth::user() returns null in Online.php model but user logged in. For example in some View or in routes.php it returns valid user object.
May not be very clear, because I badly know English. If that write in comments and I will try to describe the issue in detail