Level 34
@mehrdad70 is your product is the Course?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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();
});
}
Please or to participate in this conversation.