Unlike withSum, laravel eloquent withAvg calculates the average of the relational model column. So in this laravel 9 withAvg tutorial, I will show you an example of laravel 9 eloquent withavg. Assume we have a posts table and comments table and a post is related to comments with has many relationships. Now we want to calculate the average of vote column of every post from the comments table. How we can do that?

Using withAvg() eloquent method, we can easily do it. Let's see the example code of laravel eloquent withavg:

laravel-withavg-query-example

Now look at that our comments table:

<?php

use App\Models\Post;
use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(Post::class)
                ->constrained()
                ->cascadeOnUpdate()
                ->cascadeOnDelete();
            $table->foreignIdFor(User::class)
                ->constrained()
                ->cascadeOnUpdate()
                ->cascadeOnDelete();
            $table->string('comment');
            $table->integer('vote')->default(0);
            $table->boolean('is_approved')->default(false);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('comments');
    }
};

 

Now update the Post model like this:

app\Models\Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Post extends Model
{
    use HasFactory;

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

 

Now see the example code of laravel 9 withavg example

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class TutorialController extends Controller
{   
    /**
     * Tutorial from LARAVELIA
     */
    public function index()
    {   
        return Post::withAvg('comments','vote')->get();
    }
}

 

Remember comments table has a vote column. Now see the output:

[
    {
        "id": 1,
        "user_id": 1,
        "title": "Omnis cupiditate sed quia tempora.",
        "post_views": 12,
        "is_published": 1,
        "created_at": "2023-01-29T08:49:59.000000Z",
        "updated_at": "2023-01-29T08:49:59.000000Z",
        "comments_avg_vote": "34.5000"
    },
    {
        "id": 2,
        "user_id": 2,
        "title": "Enim sed pariatur veritatis animi.",
        "post_views": 30,
        "is_published": 1,
        "created_at": "2023-01-29T08:49:59.000000Z",
        "updated_at": "2023-01-29T08:49:59.000000Z",
        "comments_avg_vote": "10.0000"
    }
]

 

Read also: Laravel Eloquent WithSum Nested Query Example

 

Conclusion

In this laravel with avg laravel tutorial,  I have tried my best to let you know how to write a query with withavg in laravel 9. Hope now after completing this laravel 9 eloquent withavg example tutorial, you will know laravel 9 withavg example.