Browse Source

Added field validation, added saving into json file

AItEKS 1 week ago
parent
commit
fb00d7636a
2 changed files with 22 additions and 10 deletions
  1. 20 4
      form-app/app/Http/Controllers/FormController.php
  2. 2 6
      form-app/routes/web.php

+ 20 - 4
form-app/app/Http/Controllers/FormController.php

@@ -3,6 +3,7 @@
 namespace App\Http\Controllers;
 
 use Illuminate\Http\Request;
+use Illuminate\Support\Facades\File;
 
 class FormController extends Controller
 {
@@ -14,11 +15,26 @@ class FormController extends Controller
     public function submit(Request $request)
     {
         $validated = $request->validate([
-            'name' => 'required|min:3',
-            'email' => 'required|email',
-            'message' => 'required|min:10'
+            'name' => 'required|string|min:3|max:15',
+            'email' => 'required|email|max:50',
+            'message' => 'required|string|min:10|max:100'
         ]);
 
-        return back()->with('success', 'Форма успешно отправлена! Привет, ' . $request->name);
+        $path = storage_path('app/forms/contacts.json');
+
+        File::ensureDirectoryExists(dirname($path));
+
+        $data = [];
+        if (File::exists($path)) {
+            $content = File::get($path);
+            $data = json_decode($content, true) ?: [];
+        }
+
+        $validated['created_at'] = now()->toDateTimeString();
+        $data[] = $validated;
+
+        File::put($path, json_encode($data, JSON_UNESCAPED_UNICODE));
+
+        return redirect()->back()->with('success', 'Данные сохранены!');
     }
 }

+ 2 - 6
form-app/routes/web.php

@@ -3,9 +3,5 @@
 use Illuminate\Support\Facades\Route;
 use App\Http\Controllers\FormController;
 
-Route::get('/', function () {
-    return view('welcome');
-});
-
-Route::get('/form', [FormController::class, 'index'])->name('form');
-Route::post('/form', [FormController::class, 'submit'])->name('form.submit'); 
+Route::get('/', [FormController::class, 'index'])->name('form');
+Route::post('/', [FormController::class, 'submit'])->name('form.submit');