Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

binggle's avatar

how to get model id in Eloquent model ?

hi

I want to get sum of coins table with where in User Model.

class User extends Model
{

  public function today_charge()
  {
    $self = self::class;

    $sum = DB::table('coins')->where('user_id', $self->id)
        ->where('div', 'charge')->where('status', 'confirmed')->sum('amount');
    return $sum;

  }

}

How can I access self->id ?

0 likes
3 replies
Sergiu17's avatar
Sergiu17
Best Answer
Level 60
$this->id // does this work?
2 likes
Snapey's avatar

Why this way. You are inside the user object, why not just use $this

  public function today_charge()
  {

    return DB::table('coins')->where('user_id', $this->id)
        ->where('div', 'charge')->where('status', 'confirmed')->sum('amount');

  }
1 like

Please or to participate in this conversation.