Trying to filter by price

I have course search everything works. But i don’t know how to make filter by price? When i filter by price, it’s filter but it’s filters all courses. But it must filter last filtered courses not all courses. and i don’t know how to do it can anyone please help me with this?

 $courses = Course::when($r->mainCat, function ($query) use ($mainCat) {
            $courseIdsArray = Direction::whereIn('course_category_id', $mainCat)->pluck('course_id')->toArray();
            return $query->whereIn('id', $courseIdsArray);
        })->when($r->level, function ($query, $level) {
            return $query->where('level', 'like', "%{$level}%");
        })->when($categories && count($categories) > 0, function ($query) use ($categories) {
            return $query->whereIn('course_category_id', $categories);
        })


->when($r->price && in_array($r->price, ['more-expensive', 'less-expensive']), function ($query) use ($r) {
            return $query->orderBy('price', $r->price == 'less-expensive' ? 'asc' : 'desc');
        })


->paginate(18)->appends($r->query());

if someone will filter courses by categories and after that he will filter by courses by price it must filter current categories courses by price and now it’s filtering all courses by price.