Skip to content

Commit 77cb89f

Browse files
committed
Prevent users from creating more than 5 forum threads per day #1161
1 parent cca18ae commit 77cb89f

File tree

2 files changed

+19
-13
lines changed

2 files changed

+19
-13
lines changed

app/Http/Controllers/Forum/ThreadsController.php

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -81,30 +81,27 @@ public function show(Thread $thread)
8181
return view('forum.threads.show', compact('thread', 'moderators'));
8282
}
8383

84-
public function create(): View
84+
public function create()
8585
{
8686
$tags = Tag::all();
8787
$selectedTags = old('tags') ?: [];
8888

89+
$threadCount = Auth::user()->threadsCountToday();
90+
if ($threadCount >= 5) {
91+
$this->error('You can only post a maximum of 5 threads per day.');
92+
return redirect()->route('forum');
93+
}
94+
8995
return view('forum.threads.create', ['tags' => $tags, 'selectedTags' => $selectedTags]);
9096
}
9197

9298
public function store(ThreadRequest $request): RedirectResponse
9399
{
94-
$userId = Auth::id(); // Get the authenticated user's ID
95-
$midnight = now()->endOfDay();
96-
$remainingSeconds = $midnight->diffInSeconds(now());
97-
98-
// Count the threads posted by the user today
99-
$cacheKey = "user_threads_count_{$userId}";
100-
$threadCount = Cache::remember($cacheKey, $remainingSeconds, function () use ($userId) {
101-
return Thread::where('author_id', $userId)
102-
->where('created_at', '>=', now()->startOfDay())
103-
->count();
104-
});
100+
101+
$threadCount = Auth::user()->threadsCountToday();
105102

106103
// Check if the user has reached the limit
107-
if ($threadCount >= getenv('APP_MAX_THREAD_COUNT')) {
104+
if ($threadCount >= 5) {
108105
$this->error('You can only post a maximum of 5 threads per day.');
109106
return redirect()->route('forum');
110107
}

app/Models/User.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use App\Concerns\HasTimestamps;
66
use App\Concerns\PreparesSearch;
77
use App\Enums\NotificationType;
8+
use Carbon\Carbon;
89
use Illuminate\Contracts\Auth\MustVerifyEmail;
910
use Illuminate\Database\Eloquent\Builder;
1011
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -196,6 +197,14 @@ public function countThreads(): int
196197
return $this->threadsRelation()->count();
197198
}
198199

200+
201+
public function threadsCountToday(): int
202+
{
203+
return $this->threadsRelation()
204+
->whereDate('created_at', Carbon::today())
205+
->count();
206+
}
207+
199208
/**
200209
* @return \Illuminate\Database\Eloquent\Collection
201210
*/

0 commit comments

Comments
 (0)