【问题标题】:The GET method is not supported for this route. Supported methods: POST / PATCH / DELETE此路由不支持 GET 方法。支持的方法:POST / PATCH / DELETE
【发布时间】:2021-02-01 20:50:55
【问题描述】:

我手动创建了一些用于自定义目的的路线。

这是我的代码:

Route::post('/dashboard/show-all-notifications', [App\Http\Controllers\DashboardController::class, 'showAllNotifications']);

表格

{!! Form::open(['method'=>'POST','action'=>['App\Http\Controllers\DashboardController@showAllNotifications']]) !!}
   {!! Form::submit('Show all notifications', ['class'=>'btn btn-sm btn-primary btn-block']) !!}   
{!! Form::close() !!}

仪表板控制器

public function showAllNotifications(Request $request)
{
    if($request->isMethod('post'))
    {
        $notifications = Auth::user()->notifications;
        return view('dashboard.showAllNotifications',compact('notifications'));
    }
    else
    {
        return abort(404);
    }
}

当我在浏览器中输入 URL(GET request) 时,它向我显示了这个错误,但它在 POST / PATCH / DELETE 表单请求上工作。如果请求是GET,我需要类似的东西,返回到404 not found.

有人知道这个错误的解决方法吗?

【问题讨论】:

    标签: laravel routes controller


    【解决方案1】:

    直接从浏览器 url 访问 post 路由会导致此错误。您可以使用Route::any()Route::match() 来处理这种情况。然后您可以检查请求方法。如果它是您想要的,请执行一些操作,否则中止到 404。

    public function showAllNotifications(Request $request) 
    {
        if ($request->isMethod('post')) {
            //do something
        } else {
            abort(404);
        }
    }
    

    为了您的信息,在创建控制器时添加 -r 或 --resource 不会解决您的问题。这些选项用于为 crud 操作添加方法。您自己的方法和路线与资源无关。

    【讨论】:

    • 我在知道它有效之前尝试过。但我错了。不工作!我再试一次。
    • 它不工作??我在回答之前进行了测试,对我来说效果很好。
    • 用控制器代码更新你的问题,这样我就可以检查你在做什么。
    • 我可以在这里看到路线不匹配。在您的问题中,路线是'/user/show-all-notifications',但在错误异常中是'/dashboard/show-all-notifications'。你在使用两条不同的路线吗??
    • 如果控制器条件确实有效,您能否检查更改 URL,如 Route::any('/dashboard/show-all-notifications', [App\Http\Controllers\DashboardController::class, 'showAllNotifications']);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2019-10-11
    • 2021-09-09
    • 2020-04-23
    • 1970-01-01
    • 2020-08-06
    相关资源
    最近更新 更多