Auth class and auth() function doesnt works in Eloquent model. (Laravel 5)

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 CarbonCarbon;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentBuilder;
use IlluminateSupportFacadesSession;
use Auth;

class Online extends Model
{
  public $table = 'sessions';

  public $timestamps = false;

  public function user()
  {
    return $this->belongsTo('AppUser');
  }

  ...

  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 AppProviders;

use IlluminateSupportServiceProvider;
use AppOnline;

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This is not a problem with Eloquent models. You are trying to get the authenticated user before sessions have even started.

For example, in app/Http/Kernel.php, you’ll see a list of middlewares. One of them is called IlluminateSessionMiddlewareStartSession, which is responsible for starting your session.

Your service provider doesn’t have access to these session data because it hasn’t started yet. Middlewares kick in later in the lifecycle.

The solution would be to create a middleware to handle this. In your custom middleware, you can add your bit of code, and it will work.

If you’re using L5.2 though, the default database session handler already includes user_id and updates it for you.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x