diff --git a/app/Http/Controllers/Forum/ThreadsController.php b/app/Http/Controllers/Forum/ThreadsController.php index ed8988a77..fdf9d76da 100644 --- a/app/Http/Controllers/Forum/ThreadsController.php +++ b/app/Http/Controllers/Forum/ThreadsController.php @@ -81,8 +81,14 @@ public function show(Thread $thread) return view('forum.threads.show', compact('thread', 'moderators')); } - public function create(): View + public function create(): RedirectResponse|View { + if (Auth::user()->hasTooManyThreadsToday()) { + $this->error('You can only post a maximum of 5 threads per day.'); + + return redirect()->route('forum'); + } + $tags = Tag::all(); $selectedTags = old('tags') ?: []; @@ -91,6 +97,12 @@ public function create(): View public function store(ThreadRequest $request): RedirectResponse { + if (Auth::user()->hasTooManyThreadsToday()) { + $this->error('You can only post a maximum of 5 threads per day.'); + + return redirect()->route('forum'); + } + $this->dispatchSync(CreateThread::fromRequest($request, $uuid = Str::uuid())); $thread = Thread::findByUuidOrFail($uuid); diff --git a/app/Models/User.php b/app/Models/User.php index 69aba8f99..3515d8420 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -5,6 +5,7 @@ use App\Concerns\HasTimestamps; use App\Concerns\PreparesSearch; use App\Enums\NotificationType; +use Carbon\Carbon; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\HasFactory; @@ -196,6 +197,20 @@ public function countThreads(): int return $this->threadsRelation()->count(); } + public function countThreadsFromToday(): int + { + $today = Carbon::today(); + + return $this->threadsRelation() + ->whereBetween('created_at', [$today, $today->copy()->endOfDay()]) + ->count(); + } + + public function hasTooManyThreadsToday(): bool + { + return $this->countThreadsFromToday() >= 5; + } + /** * @return \Illuminate\Database\Eloquent\Collection */ diff --git a/tests/Feature/ForumTest.php b/tests/Feature/ForumTest.php index b85b8672c..719c5c335 100644 --- a/tests/Feature/ForumTest.php +++ b/tests/Feature/ForumTest.php @@ -83,6 +83,22 @@ ->assertSessionHas('success', 'Thread successfully created!'); }); +test('users cannot create more than 5 threads per day', function () { + $tag = Tag::factory()->create(['name' => 'Test Tag']); + + $user = $this->login(); + + Thread::factory()->count(5)->create(['author_id' => $user->id(), 'created_at' => now()]); + + $this->post('/forum/create-thread', [ + 'subject' => 'How to work with Eloquent?', + 'body' => 'This text explains how to work with Eloquent.', + 'tags' => [$tag->id()], + ]) + ->assertRedirect('/forum') + ->assertSessionHas('error', 'You can only post a maximum of 5 threads per day.'); +})->only(); + test('users can edit a thread', function () { $user = $this->createUser(); $tag = Tag::factory()->create(['name' => 'Test Tag']);