| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\File;
- use Carbon\Carbon;
- class FormController extends Controller
- {
- private $path;
- public function __construct()
- {
- $this->path = storage_path('app/forms/contacts.json');
- }
-
- public function index()
- {
- return view('form');
- }
- public function submit(Request $request)
- {
- $validated = $request->validate([
- 'name' => 'required|string|min:3|max:15',
- 'email' => 'required|email|max:50',
- 'message' => 'required|string|min:10|max:100'
- ]);
- File::ensureDirectoryExists(dirname($this->path));
- $data = [];
- if (File::exists($this->path)) {
- $content = File::get($this->path);
- $data = json_decode($content, true) ?: [];
- }
- $validated['created_at'] = now()->toDateTimeString();
- $data[] = $validated;
- File::put($this->path, json_encode($data, JSON_UNESCAPED_UNICODE));
- return redirect()->back()->with('success', 'Данные сохранены!');
- }
- public function showData()
- {
- $data = [];
- if (File::exists($this->path)) {
- $content = File::get($this->path);
- $data = json_decode($content, true) ?: [];
- }
- $submissions = collect($data)->map(function ($item) {
- return (object) [
- 'name' => $item['name'],
- 'email' => $item['email'],
- 'message' => $item['message'],
- 'created_at' => Carbon::parse($item['created_at'])
- ];
- }) -> sortBy('createdAt');
- return view('admin', compact('submissions'));
- }
- }
|