douxin8610 2016-01-17 04:45
浏览 59
已采纳

Auth类和auth()函数在Eloquent模型中不起作用。 (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 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

  • 写回答

1条回答 默认 最新

  • dqhdpppm02183 2016-01-17 05:59
    关注

    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 Illuminate\Session\Middleware\StartSession, 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加