i229194964
@i229194964
Веб разработчик

Не сохряняет значение вообще в таблицу в чем проблема может быть?

Controller
<?php

namespace App\Http\Controllers\Voyager;
use Illuminate\Support\Facades\Log;
use App\Exports\MyObjectsExport;
use App\Http\Controllers\Controller;
use App\Imports\MyObjectsImport;
use App\Models\MyObject;
use App\Models\ObjectCoordinate;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\DB;

class VoyagerMyObjectController extends Controller
{
    public function index(Request $request)
    {
        $searchQuery = $request->input('search');

        if ($searchQuery) {
            $objects = MyObject::where('name', 'LIKE', "%$searchQuery%")
                ->orWhere('address', 'LIKE', "%$searchQuery%")
                ->paginate(10);
        } else {
            $objects = MyObject::paginate(10);
        }

        return view('admin.objects.index', compact('objects'));
    }
    public function create()
    {
        return view('admin.objects.create');
    }

    public function export()
    {
        $fileName = 'my_objects.xlsx';

        return Excel::download(new MyObjectsExport(), $fileName);
    }

    public function store(Request $request)
    {
        DB::enableQueryLog();        $validatedData = $request->validate([
            'name' => 'required',
            'latitude' => 'required',
            'longitude' => 'required',
            'municipal_entity' => 'nullable',
            'platform_name' => 'nullable',
            'platform_format' => 'nullable',
            'total_area' => 'nullable',
            'object_type' => 'nullable',
            'address' => 'nullable',
            'nearest_city' => 'nullable',
            'economic_activities' => 'nullable',
            'ownership_form' => 'nullable',
            'free_land_area' => 'nullable',
            'cadastre_number' => 'nullable',
            'cadastre_value' => 'nullable',
            'vri' => 'nullable',
            'coordTableName' => 'required',
            'land_survey' => 'nullable',
            'land_category' => 'nullable',
            'planning_documents' => 'nullable',
            'water_supply' => 'nullable',
            'gas_supply' => 'boolean',
            'electricity_supply' => 'boolean',
            'waste_removal' => 'boolean',
            'road_access' => 'boolean',
            'railway' => 'boolean',

        ]);

        try {
            // Шаг 1: Валидация и получение координат
            $validatedData = $request->validate([
                // ... ваши правила валидации ...
            ]);

            $coordinates = $request->input('coordTableName');
            $coordinatesArray = explode(',', $coordinates);

            // Шаг 2: Создание объекта и координат
            if (count($coordinatesArray) != 2) {
                return redirect('/admin/my-objects')->with('error', 'Некорректный формат координат');
            }

            $latitude = trim($coordinatesArray[0]);
            $longitude = trim($coordinatesArray[1]);

            $validatedData['gas_supply'] = $request->has('gas_supply');
            $validatedData['electricity_supply'] = $request->has('electricity_supply');
            $validatedData['waste_removal'] = $request->has('waste_removal');
            $validatedData['road_access'] = $request->has('road_access');
            $validatedData['railway'] = $request->has('railway');

            $object = MyObject::create($validatedData);

            $coordinateData = [
                'latitude' => $latitude,
                'longitude' => $longitude,
                'object_id' => $object->id,
            ];

            ObjectCoordinate::create($coordinateData);

            // Шаг 3: Обработка дополнительных координат
            $additionalCoordinates = [];
            for ($i = 1; $i <= 1000; $i++) {
                $additionalLatitudeKey = "latitude{$i}";
                $additionalLongitudeKey = "longitude{$i}";

                if ($request->has($additionalLatitudeKey) && $request->has($additionalLongitudeKey)) {
                    $additionalLatitude = trim($request->input($additionalLatitudeKey));
                    $additionalLongitude = trim($request->input($additionalLongitudeKey));
                    $additionalCoordinates[] = [
                        'latitude' => $additionalLatitude,
                        'longitude' => $additionalLongitude,
                    ];
                }
            }
            $object->additional_coordinates = $additionalCoordinates;
            $object->save();

            // Шаг 4: Сохранение изменений
            return redirect('/admin/my-objects')->with('success', 'Объект успешно создан');

        } catch (\Exception $e) {
            // Логируем ошибку
            \Log::error($e);

            // Возвращаем пользователю сообщение об ошибке
            return redirect('/admin/my-objects')->with('error', 'Произошла ошибка при сохранении: ' . $e->getMessage());
        }
    }


    public function edit($id)
    {
        $object = MyObject::find($id);
        $coordTableName = $object->coordTableName ?? null;

        return view('admin.objects.edit', compact('object', 'coordTableName'));
    }

    public function update(Request $request, $id)
    {

        $validatedData = $request->validate([
            'name' => 'required',
            'municipal_entity' => 'nullable',
            'platform_name' => 'nullable',
            'platform_format' => 'nullable',
            'total_area' => 'nullable',
            'object_type' => 'nullable',
            'address' => 'nullable',
            'nearest_city' => 'nullable',
            'economic_activities' => 'nullable',
            'ownership_form' => 'nullable',
            'free_land_area' => 'nullable',
            'cadastre_number' => 'nullable',
            'cadastre_value' => 'nullable',
            'vri' => 'nullable',
            'land_survey' => 'nullable',
            'land_category' => 'nullable',
            'planning_documents' => 'nullable',
            'water_supply' => 'nullable',
            'gas_supply' => 'boolean',
            'electricity_supply' => 'boolean',
            'waste_removal' => 'boolean',
            'road_access' => 'boolean',
            'railway' => 'boolean',
            'coordTableName' => 'nullable',
            'latitude' => 'nullable',
            'longitude' => 'nullable',
            // ... другие правила валидации для дополнительных координат ...
        ]);


        try {
            $object = MyObject::find($id);

            $coordinates = $request->input('coordTableName');
            $coordinatesArray = explode(',', $coordinates);

            if (count($coordinatesArray) >= 2) {
                $object->latitude = trim($coordinatesArray[0]);
                $object->longitude = trim($coordinatesArray[1]);
            } else {
                return redirect("/admin/my-objects/{$id}/edit")->with('error', 'Некорректный формат координат');
            }

            $additionalCoordinates = [];
            for ($i = 1; $i <= 1000; $i++) {
                $additionalLatitudeKey = "latitude{$i}";
                $additionalLongitudeKey = "longitude{$i}";

                if ($request->has($additionalLatitudeKey) && $request->has($additionalLongitudeKey)) {
                    $additionalLatitude = trim($request->input($additionalLatitudeKey));
                    $additionalLongitude = trim($request->input($additionalLongitudeKey));
                    $additionalCoordinates[] = ['latitude' => $additionalLatitude, 'longitude' => $additionalLongitude];
                }
            }

            // Остальные поля объекта
            $object->update($validatedData);

            // В методе update
            Log::debug('Validated Data:', $validatedData);
            Log::debug('Coordinates:', $coordinates);
            Log::debug('Additional Coordinates:', $additionalCoordinates);

// После обновления остальных полей объекта и перед сохранением
            Log::debug('Object before saving:', $object);

            $object->save();

            return redirect('/admin/my-objects')->with('success', 'Объект успешно обновлен');
        } catch (\Exception $e) {
            return redirect("/admin/my-objects/{$id}/edit")->with('error', 'Произошла ошибка: ' . $e->getMessage());
        }
    }

    public function destroy($id)
    {
        MyObject::destroy($id);
        return redirect()->route('voyager.my-objects.index')->with('success', 'Объект успешно удален');
    }
}
  • Вопрос задан
  • 59 просмотров
Пригласить эксперта
Ответы на вопрос 1
delphinpro
@delphinpro Куратор тега Laravel
frontend developer
Если прямо так и написано, то ничего и не сохранится, $validatedData будет пуст. И зачем второй раз валидировать, если выше уже было?
$validatedData = $request->validate([
                // ... ваши правила валидации ...
            ]);


Ну и здесь просто предположу
$object = MyObject::create($validatedData);

Чтобы модель получила данные, у нее должно быть заполнено поле $fillable. Модель не вижу, не знаю, как у вас.

А так все выглядит вполне корректным.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы