首页 > 解决方案 > 试图在 uselogin.php 中获取非对象的属性

问题描述

嗨,我正在使用 larave,但这是代码和行 if(is_null($StudentId)) $StudentId = Auth::user()->students_ID;导致试图获取非对象错误的属性

namespace App\Models;


use App\Core\Actions;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class UserLog extends Model {
    protected $fillable = ['student_id','action','time'];
    public $timestamps = false;

    public static function Log($Action,$StudentId = null) {
       if(is_null($StudentId)) $StudentId = Auth::user()->students_ID;

        if(self::CheckLastMinute($Action,$StudentId)) return;
        self::create([
            'student_id' => $StudentId,
            'action' => $Action,
            'time' => date("Y-m-d H:i:s")
        ]);
    }

    public static function CheckLastMinute($Action,$StudentId = null) {
        if(is_null($StudentId)) $StudentId = Auth::user()->students_ID;
        return self::where('action',$Action)
            ->where('student_id',$StudentId)
            ->where('time','>=',Carbon::now()->subMinutes(1)->toDateTimeString())
            ->count();
    }
}

非常抱歉,丢失的部分不知道我今天的连接速度很慢

标签: phplaravel

解决方案


假设您有一个经过身份验证的用户实例是一个坏主意。

当您没有经过身份验证的用户时,无论是在 cli 上下文中还是来宾浏览您的站点,Auth::user()都将返回 null。因此,您实际上是null->students_ID在这些上下文中调用,这就是错误的原因。


推荐阅读