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

mehrdad70's avatar

The best-selling products in Laravel

Hello friends I want to show the best selling products How can I implement this?

order model

class Order extends Model
{

    public function courses()
    {
        return $this->belongsToMany(Course::class, 'order_course', 'order_id', 'course_id');
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

}

course model

class Course extends Model
{

    public function students()
    {
        return $this->belongsToMany(User::class , 'course_user' , 'course_id' , 'user_id');
    }

    public function orders()
    {
        return $this->belongsToMany(Order::class);
    }


    public function addStudentToCourses($courses , $userId)
    {
        foreach($courses as $course) {
            if(! $this->getCourseUser($course , $userId)){
                $course->students()->attach($userId);
            }
        }
    }

    public function getCourseUser(Course $course , $userId)
    {
        return $course->students()->where('id' , $userId)->first();
    }


}

order table

    public function up()
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->string('code')->nullable()->unique();
            $table->bigInteger('price');
            $table->enum('status' , ['fail'  ,'success' , 'pending' , 'canseled']);
            $table->timestamps();
        });

        Schema::create('order_course', function (Blueprint $table) {
            $table->foreignId('order_id')->constrained('orders')->cascadeOnDelete();
            $table->foreignId('course_id')->constrained('courses')->cascadeOnDelete();

        });
    }
0 likes
7 replies
neilstee's avatar

In your Course model:

public function sortByBestSelling()
{
        return $this->sortBy(function($course) {
			return $course->orders->count();
		});
}

so in your code:

Course::sortByBestSelling->get();
neilstee's avatar

something like this but you might need to get orders() first so you can count it inside the closure.

mehrdad70's avatar

This solution did not solve the problem):

Please or to participate in this conversation.