Метод DELETE не поддерживается для этого маршрута?

Есть сайт на Laravel 8.54.0 - простой конструктор html сайтов.
Теперь к самой проблеме.

Проблема такая, не срабатывает удаление проекта при нажатии на кнопку "удалить сайт". После нажатия, визуально ничего не происходит, проект не удаляется.

Я обратился к хостинг провайдеру за помощь, вот, что мне ответила поддержка.

exception: "Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException"
file: "/var/www/www-root/data/www/ВАШСАЙТ/vendor/laravel/framework/src/Illuminate/Routing/AbstractRouteCollection.php"
line: 117
message: "The DELETE method is not supported for this route. Supported methods: GET, HEAD, PUT."

Вот файл роутов web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

use App\Http\Controllers\ElementsController;
use App\Http\Controllers\ExportProjectToFTPController;
use App\Http\Controllers\ProjectDownloadController;
use App\Http\Controllers\ProjectsController;
use App\Http\Controllers\ProjectSettingsController;
use App\Http\Controllers\ProjectThumbnailController;
use App\Http\Controllers\TemplatesController;

Route::group(['prefix' => 'secure'], function () {

    //templates
    Route::get('templates', [TemplatesController::class, 'index']);
    Route::get('templates/{name}', [TemplatesController::class, 'show']);
    Route::post('templates', [TemplatesController::class, 'store']);
    Route::put('templates/{name}', [TemplatesController::class, 'update']);
    Route::delete('templates', [TemplatesController::class, 'destroy']);

    //projects
    Route::get('projects', [ProjectsController::class, 'index']);
    Route::post('projects/{project}/export/ftp', [ExportProjectToFTPController::class, 'export']);
    Route::post('projects', [ProjectsController::class, 'store']);
    Route::get('projects/{id}', [ProjectsController::class, 'show']);
    Route::put('projects/{id}', [ProjectsController::class, 'update']);
    Route::put('projects/{project}/toggle-state', [ProjectsController::class, 'toggleState']);
    Route::delete('projects', [ProjectsController::class, 'destroy']);
    Route::post('projects/{id}/generate-thumbnail', [ProjectThumbnailController::class, 'store']);
    Route::get('projects/{project}/download', [ProjectDownloadController::class, 'download']);

    // project settings
    Route::post('projects/{project}/settings', [ProjectSettingsController::class, 'store']);

    //elements
    Route::get('elements/custom.js', [ElementsController::class, 'custom']);
});

Route::get('sites/{name}/{page?}', 'UserSiteController@show')->name('user-site-regular');

//FRONT-END ROUTES THAT NEED TO BE PRE-RENDERED
Route::get('/', '\Common\Core\Controllers\HomeController@show')
    ->middleware('prerenderIfCrawler:homepage');

Route::get('{all}', '\Common\Core\Controllers\HomeController@show')->where('all', '.*');


Вот файл ProjectsController.php

<?php namespace App\Http\Controllers;

use App\Project;
use App\Services\ProjectRepository;
use Common\Core\BaseController;
use Common\Database\Datasource\DatasourceFilters;
use Common\Database\Datasource\MysqlDataSource;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class ProjectsController extends BaseController
{
    /**
     * @var Request
     */
    private $request;

    /**
     * @var Project
     */
    private $project;

    /**
     * @var ProjectRepository
     */
    private $repository;

    public function __construct(
        Request $request,
        Project $project,
        ProjectRepository $repository
    ) {
        $this->request = $request;
        $this->project = $project;
        $this->repository = $repository;
    }
    public function index()
    {
        $builder = $this->project->with(['domain', 'users']);
        $filters = new DatasourceFilters(
            $this->request->get('filters'),
            $builder->getModel(),
        );
        $userId =
            $this->request->get('user_id') ?? $filters->getAndRemove('user_id');

        $this->authorize('index', [Project::class, $userId]);

        if ($userId) {
            $builder->whereHas('users', function (Builder $q) use ($userId) {
                return $q->where('users.id', $userId);
            });
        }

        if (
            $this->request->has('published') &&
            $this->request->get('published') !== 'all'
        ) {
            $builder->where('published', $this->request->get('published'));
        }

        $datasource = new MysqlDataSource(
            $builder,
            $this->request->all(),
            $filters,
        );

        return $this->success(['pagination' => $datasource->paginate()]);
    }

    public function show($id)
    {
        $project = $this->project->with('pages', 'users')->findOrFail($id);

        $this->authorize('show', $project);

        $project = $this->repository->load($project);

        return $this->success(['project' => $project]);
    }

    public function update(int $id)
    {
        $project = $this->project->with('users')->find($id);

        $this->authorize('update', $project);

        $this->validate($this->request, [
            'name' => 'string|min:3|max:255',
            'css' => 'nullable|string|min:1',
            'js' => 'nullable|string|min:1',
            'template' => 'nullable|string|min:1|max:255',
            'custom_element_css' => 'nullable|string|min:1',
            'published' => 'boolean',
            'pages' => 'array',
            'pages.*' => 'array',
        ]);

        $this->repository->update($project, $this->request->all());

        return $this->success(['project' => $this->repository->load($project)]);
    }

    public function toggleState(Project $project)
    {
        $this->authorize('update', $project);

        $project
            ->fill(['published' => $this->request->get('published')])
            ->save();

        return $this->success(['project' => $project]);
    }

    public function store()
    {
        $this->authorize('store', Project::class);

        $this->validate($this->request, [
            'name' => 'required|string|min:3|max:255|unique:projects',
            'slug' => 'string|min:3|max:30|unique:projects',
            'css' => 'nullable|string|min:1|max:255',
            'js' => 'nullable|string|min:1|max:255',
            'template_name' => 'nullable|string',
            'published' => 'boolean',
        ]);

        $project = $this->repository->create($this->request->all());

        return $this->success(['project' => $this->repository->load($project)]);
    }

    public function destroy(string $ids)
    {
        $projectIds = explode(',', $ids);
        foreach ($projectIds as $id) {
            $project = $this->project->findOrFail($id);

            $this->authorize('destroy', $project);

            $this->repository->delete($project);
        }

        return $this->success();
    }
}
  • Вопрос задан
  • 144 просмотра
Пригласить эксперта
Ответы на вопрос 1
pLavrenov
@pLavrenov
Разработка сайтов
Route::delete('projects', [ProjectsController::class, 'destroy']);

Тут нет параметров
public function destroy(string $ids)
тут есть, да еще через запятую. ужс

99% - ошибка в неправильной отправке данных со стороны клиента.
id надо отправлять в массиве тела запроса, а не вот это вот все, так как удаление все-равно должно быть POST

----

Эта часть не имеет смысла.
public function __construct(
        Request $request,
        Project $project,
        .....
 )

вот это
public function update(int $id)
{
    $project = $this->project->with('users')->find($id);

    $this->authorize('update', $project);

    $this->validate($this->request, [
        'name' => 'string|min:3|max:255',
        'css' => 'nullable|string|min:1',
        'js' => 'nullable|string|min:1',
        'template' => 'nullable|string|min:1|max:255',
        'custom_element_css' => 'nullable|string|min:1',
        'published' => 'boolean',
        'pages' => 'array',
        'pages.*' => 'array',
    ]);

    $this->repository->update($project, $this->request->all());

    return $this->success(['project' => $this->repository->load($project)]);
}

превращается в это
public function update(Project $project, ProjectRequest $request)
{
    $this->authorize('update', $project);

    return response()->json([
        'success' => true,
        'data' => $this->projectRepository->update($project, $request->all()),
    ]);
}
Ответ написан
Комментировать
Ваш ответ на вопрос

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

Похожие вопросы