|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Livewire; |
| 4 | + |
| 5 | +use App\Models\Lead; |
| 6 | +use App\Notifications\LeadReceived; |
| 7 | +use App\Notifications\NewLeadSubmitted; |
| 8 | +use App\Rules\Turnstile; |
| 9 | +use Illuminate\Support\Facades\Notification; |
| 10 | +use Illuminate\Support\Facades\RateLimiter; |
| 11 | +use Livewire\Component; |
| 12 | + |
| 13 | +class LeadSubmissionForm extends Component |
| 14 | +{ |
| 15 | + public string $name = ''; |
| 16 | + |
| 17 | + public string $email = ''; |
| 18 | + |
| 19 | + public string $company = ''; |
| 20 | + |
| 21 | + public string $description = ''; |
| 22 | + |
| 23 | + public string $budget = ''; |
| 24 | + |
| 25 | + public string $turnstileToken = ''; |
| 26 | + |
| 27 | + public bool $submitted = false; |
| 28 | + |
| 29 | + protected function rules(): array |
| 30 | + { |
| 31 | + $rules = [ |
| 32 | + 'name' => ['required', 'string', 'max:255'], |
| 33 | + 'email' => ['required', 'email', 'max:255'], |
| 34 | + 'company' => ['required', 'string', 'max:255'], |
| 35 | + 'description' => ['required', 'string', 'max:5000'], |
| 36 | + 'budget' => ['required', 'string', 'in:'.implode(',', array_keys(Lead::BUDGETS))], |
| 37 | + ]; |
| 38 | + |
| 39 | + if (config('services.turnstile.secret_key')) { |
| 40 | + $rules['turnstileToken'] = ['required', new Turnstile]; |
| 41 | + } |
| 42 | + |
| 43 | + return $rules; |
| 44 | + } |
| 45 | + |
| 46 | + public function messages(): array |
| 47 | + { |
| 48 | + return [ |
| 49 | + 'budget.in' => 'Please select a budget range.', |
| 50 | + 'turnstileToken.required' => 'Please complete the security check.', |
| 51 | + ]; |
| 52 | + } |
| 53 | + |
| 54 | + public function submit(): void |
| 55 | + { |
| 56 | + $key = 'leads:'.request()->ip(); |
| 57 | + |
| 58 | + if (RateLimiter::tooManyAttempts($key, 5)) { |
| 59 | + $seconds = RateLimiter::availableIn($key); |
| 60 | + $this->addError('form', "Too many submissions. Please try again in {$seconds} seconds."); |
| 61 | + |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + $this->validate(); |
| 66 | + |
| 67 | + RateLimiter::hit($key, 60); |
| 68 | + |
| 69 | + $lead = Lead::create([ |
| 70 | + 'name' => $this->name, |
| 71 | + 'email' => $this->email, |
| 72 | + 'company' => $this->company, |
| 73 | + 'description' => $this->description, |
| 74 | + 'budget' => $this->budget, |
| 75 | + 'ip_address' => request()->ip(), |
| 76 | + ]); |
| 77 | + |
| 78 | + $lead->notify(new LeadReceived); |
| 79 | + |
| 80 | + Notification:: route( 'mail', '[email protected]') |
| 81 | + ->notify(new NewLeadSubmitted($lead)); |
| 82 | + |
| 83 | + $this->submitted = true; |
| 84 | + } |
| 85 | + |
| 86 | + public function render() |
| 87 | + { |
| 88 | + return view('livewire.lead-submission-form', [ |
| 89 | + 'budgets' => Lead::BUDGETS, |
| 90 | + ]); |
| 91 | + } |
| 92 | +} |
0 commit comments