0

Hi im using larave but this the code and line if(is_null($StudentId)) $StudentId = Auth::user()->students_ID; results in trying to get property of non object error

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();
    }
}

terribly sorry the missing parts had no idea im having a really bad slow connection today

MetalSaint
  • 53
  • 10

1 Answers1

0

It's a bad idea to assume you have an authenticated user instance.

When you don't have an authenticated user, either in a cli context or a guest browsing your site, Auth::user() will return null. So you're essentially calling null->students_ID in those contexts which is the reason for the error.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95