Laravel по-русски

Русское сообщество разработки на PHP-фреймворке Laravel.

Ты не вошёл. Вход тут.

#1 Re: Laravel 6/7/8/9/10 » Route not defined » 07.02.2022 18:24:42

ter

дело не в контроллере, а в том, что не даёт повесить 3 маршрута на один контроллер.
также

задействуем метод контроллера 'update'

- это будет 3-й метод (или маршрут) (кроме index и edit), и тоже не будет работать

чем сейчас он неправильный (именно контроллер)?

#2 Re: Laravel 6/7/8/9/10 » Route not defined » 06.02.2022 19:59:37

ter

Спасибо! Вместо 4-х маршрутов сделал 3, теперь пишет Route [admin_tournaments_save] not defined. Тогда должно быть только 2? Но там 3 состояния (или больше). 1 - список всех турниров, 2 - редактирование, 3 - добавление нового, 4 - сохранение. Сейчас добавления нового вообще нету, и уже не работает.
то есть, список - это "index", редактирование или добавление - это "edit" с параметром (bool edit) в request, сохранение - это "save" (с параметром, новая ли это запись, или старая - тот же bool edit в request)

сейчас такие

    Route::get('/adm/tournaments',        'Adm\TournamentController@index')->middleware(["admin"])->name("admin_tournaments_index");
    Route::post('/adm/tournaments',        'Adm\TournamentController@save')->middleware(["admin"])->name("admin_tournaments_save");
    Route::post('/adm/tournaments',        'Adm\TournamentController@edit')->middleware(["admin"])->name("admin_tournaments_edit");  

то есть, он хочет по одному на каждый get  и post?

Далее создаем метод edit - в нём осуществляем редактирование записи.(GET)

а почему "edit" - get, а не post? тогда пропадёт index? он, вроде, оставляет последний из указанных

валидацию пока не выносил

#3 Re: Laravel 6/7/8/9/10 » Route not defined » 04.02.2022 23:36:33

ter
class TournamentController extends AdmController
{
    use ValidatesRequests;

    public function index_edit(Request $request)
    {
        $tourTypes = TournamentTypes::all();
        $oldTournament = Tournament::where("id", "=", $request->get('tournament_id'))->first();
        $accountTypes = AbstractAccount::getAllOperableAccounts();
        $tournaments = Tournament::all()->where("status", ">", -1);

        return view("adm.tournaments.index", [
            "tour_types" => $tourTypes,
            "old_tournament" => $oldTournament,
            "accountTypes" => $accountTypes,
            "tournaments" => $tournaments,
            "edit" => true
        ]);
    }
...
}

если целиком, то

<?php

namespace App\Http\Controllers\Adm;

use App\Models\Accounts\BaseAccounts\AbstractAccount;
use App\Tournament;
use App\TournamentTypes;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TournamentController extends AdmController
{
    use ValidatesRequests;

    public function index_edit(Request $request)
    {
        $tourTypes = TournamentTypes::all();
        $oldTournament = Tournament::where("id", "=", $request->get('tournament_id'))->first();
        $accountTypes = AbstractAccount::getAllOperableAccounts();
        $tournaments = Tournament::all()->where("status", ">", -1);

        return view("adm.tournaments.index", [
            "tour_types" => $tourTypes,
            "old_tournament" => $oldTournament,
            "accountTypes" => $accountTypes,
            "tournaments" => $tournaments,
            "edit" => true
        ]);
    }

    public function index_add()
    {
        $tourTypes = TournamentTypes::all();
        $oldTournament = Tournament::where("id", ">", 0)->orderBy("id", "DESC")->first();
        $accountTypes = AbstractAccount::getAllOperableAccounts();
        $tournaments = Tournament::all()->where("status", ">", -1);

        return view("adm.tournaments.index", [
            "tour_types" => $tourTypes,
            "old_tournament" => $oldTournament,
            "accountTypes" => $accountTypes,
            "tournaments" => $tournaments,
            "edit" => false
        ]);
    }    

    public function save(Request $request)
    {

        $rules = [
            'title' => ['string', 'min:3', 'max:255'],
            'game_type' => ['integer', 'min:0'],
            'rebay' => ['array', 'nullable'],
            'win_in_match' => ['integer', 'min:0'],
            'money_type' => ['integer', 'min:0'],
            'buy_in' => ['integer', 'min:0'],
            'prize' => ['integer', 'min:0'],
            'bounty' => ['integer', 'min:0'],
            'bounty_percent' => ['integer', 'min:0'],
            'date' => ['date'],
            'registration_date' => ['date'],
            'min_players' => ['integer', 'min:1'],
            'game_time' => ['integer', 'min:0', 'max:2'],
            'regards' => ['array'],
            'color' => ['string','max:255'],
            'type_id'  => ['integer'],
            'is_repeat'  => ['integer',"nullable"],
            'is_spectate'  => ['integer',"nullable"],
        ];

        $this->validate($request, $rules);


        DB::beginTransaction();

        try {
            $tour = new Tournament();

            $tour->game_type = $request->get('game_type');
            $tour->win_in_match = $request->get('win_in_match');
            $tour->money_type = 2; // $request->get('money_type')
            $tour->title = $request->get('title');
            $tour->prize = $request->get('prize');
            $tour->bounty = $request->get('bounty');
            $tour->bounty_percent = $request->get('bounty_percent');
            $tour->buy_in = $request->get('buy_in');
            $tour->status = 0;
            $tour->date = $request->get('date');
            $tour->registration_date = $request->get('registration_date');
            $tour->game_time = $request->get('game_time');
            $tour->min_players = $request->get('min_players');
            $tour->regards = json_encode(array_filter($request->get('regards')));
            $tour->color = $request->get('color');
            $tour->type_id = $request->get('type_id');
            $tour->prize_type = $request->get('prize_type');
            $tour->is_repeat = $request->get('is_repeat') ?? 0;
            $tour->save();

            if (!$tour->generateTours()) {
                throw new \Exception("Error with generate tours");
            }

        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->route("admin_tournaments_index_add")->withErrors($e->getMessage());
        }
        DB::commit();

        //return redirect()->route("admin_tournaments_index");
        return view("adm.tournaments.tour_saved", []);
    }

    public function edit(Request $request)
    {

        $rules = [
            'title' => ['string', 'min:3', 'max:255'],
            'game_type' => ['integer', 'min:0'],
            'rebay' => ['array', 'nullable'],
            'win_in_match' => ['integer', 'min:0'],
            'money_type' => ['integer', 'min:0'],
            'buy_in' => ['integer', 'min:0'],
            'prize' => ['integer', 'min:0'],
            'bounty' => ['integer', 'min:0'],
            'bounty_percent' => ['integer', 'min:0'],
            'date' => ['date'],
            'registration_date' => ['date'],
            'min_players' => ['integer', 'min:1'],
            'game_time' => ['integer', 'min:0', 'max:2'],
            'regards' => ['array'],
            'color' => ['string','max:255'],
            'type_id'  => ['integer'],
            'is_repeat'  => ['integer',"nullable"],
            'is_spectate'  => ['integer',"nullable"],
        ];

        $this->validate($request, $rules);


        DB::beginTransaction();

        try {
            $oldTournament = Tournament::where("id", "=", $request->get('tournament_id'))->first();
            $tour = $oldTournament;            

            $tour->game_type = $request->get('game_type');
            $tour->win_in_match = $request->get('win_in_match');
            $tour->money_type = 2; // $request->get('money_type')
            $tour->title = $request->get('title');
            $tour->prize = $request->get('prize');
            $tour->bounty = $request->get('bounty');
            $tour->bounty_percent = $request->get('bounty_percent');
            $tour->buy_in = $request->get('buy_in');
            $tour->status = 0;
            $tour->date = $request->get('date');
            $tour->registration_date = $request->get('registration_date');
            $tour->game_time = $request->get('game_time');
            $tour->min_players = $request->get('min_players');
            $tour->regards = json_encode(array_filter($request->get('regards')));
            $tour->color = $request->get('color');
            $tour->type_id = $request->get('type_id');
            $tour->prize_type = $request->get('prize_type');
            $tour->is_repeat = $request->get('is_repeat') ?? 0;
            $tour->save();

            if (!$tour->generateTours()) {
                throw new \Exception("Error with generate tours");
            }

        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->route("admin_tournaments_index_edit")->withErrors($e->getMessage());
        }
        DB::commit();

        //return redirect()->route("admin_tournaments_index");
        return view("adm.tournaments.tour_edited", []);
    }    
}

#4 Laravel 6/7/8/9/10 » Route not defined » 04.02.2022 17:17:41

ter
Ответов: 7

Здравствуйте. Получаю ошибку "Route [admin_tournaments_index_edit] not defined."

В web.php есть 4 похожих маршрута:

    Route::post('/adm/tournaments',        'Adm\TournamentController@index_edit')->middleware(["admin"])->name("admin_tournaments_index_edit");
    Route::get('/adm/tournaments',        'Adm\TournamentController@index_add')->middleware(["admin"])->name("admin_tournaments_index_add");
    Route::post('/adm/tournaments',
        'Adm\TournamentController@save')->middleware(["admin"])->name("admin_tournaments_save");
    Route::post('/adm/tournaments',
        'Adm\TournamentController@edit')->middleware(["admin"])->name("admin_tournaments_edit");

В "php artisan route:list" только 2 маршрута отображается:

        | GET|HEAD  | adm/tournaments                          | admin_tournaments_index_add | App\Http\Controllers\Adm\TournamentController@index_add         | web,auth,admin |
|        | POST      | adm/tournaments                          | admin_tournaments_edit      | App\Http\Controllers\Adm\TournamentController@edit              | web,auth,admin |

вызов из blade.php:

<form method="post" action="{{ route("admin_tournaments_index_edit") }}">

Можно только по одному маршруту на каждый get или post? И как тогда переделать?

Подвал раздела