title: Laravel Getting Average of data of different users using eloquent
body: <p>I have done a function where I calculate the average value of score given to different users differently . Mean Different user's scores average is calculated differently . </p>
  
  <p>I want this function to be done with the help of eloquent so that I can use the ralationships of this model </p>
  
  <pre class="lang-php prettyprint-override"><code>    $data = \DB::table('cleaning_scores')
                  -&gt;select(\DB::raw('avg(score) as avg, user_id'))
                  -&gt;groupBy('user_id')-&gt;orderBy('avg','DESC')
                  -&gt;get();  
  </code></pre>
  
  <p>This is my CleaningScore.php Model </p>
  
  <pre class="lang-php prettyprint-override"><code>    &lt;?php
  
        namespace App;
  
       use Illuminate\Database\Eloquent\Model;
  
       class CleaningScore extends Model
       {
           protected $fillable = ['user_id','score','giver_id'];
  
           public function users()
           {
              return $this-&gt;belongsTo(User::class , 'user_id');
           }
           public function givers()
           {
              return $this-&gt;belongsTo(User::class , 'giver_id');
           }
       }
  </code></pre>
  
  <p>THis is User Model </p>
  
  <pre class="lang-php prettyprint-override"><code>&lt;?php
  
  namespace App;
  
  use Illuminate\Notifications\Notifiable;
  use Illuminate\Contracts\Auth\MustVerifyEmail;
  use Illuminate\Foundation\Auth\User as Authenticatable;
  use Spatie\Permission\Traits\HasRoles;
  
  class User extends Authenticatable
  {
      use Notifiable,HasRoles;
  
      /**
       * The attributes that are mass assignable.
       *
       * @var array
       */
      protected $fillable = [
          'name', 'email', 'password','room_id'
      ];
  
      /**
       * The attributes that should be hidden for arrays.
       *
       * @var array
       */
      protected $hidden = [
          'password', 'remember_token',
      ];
  
      /**
       * The attributes that should be cast to native types.
       *
       * @var array
       */
      protected $casts = [
          'email_verified_at' =&gt; 'datetime',
      ];
  
      public function rooms()
      {
          return $this-&gt;belongsTo(Room::class , 'room_id');
      }
  
      public function scores()
      {
          return $this-&gt;hasMany(Score::class);
      }
  
      public function cleaning_scores()
      {
          return $this-&gt;hasMany(CleaningScore::class);
      }
  
      public function own_rooms()
      {
          return $this-&gt;hasMany(Room::class);
      }
  
      public function own_scores()
      {
          return $this-&gt;hasMany(CleaningScore::class);
      }
  
      public function rankings()
      {
          return $this-&gt;hasOne(Ranking::class);
      }
  }
  
  </code></pre>