' MethodNotAllowedHttpException' laravel错误

时间:2018-04-02 08:09:23

标签: laravel

所以我正在尝试更新数据库中的信息。一切都很好,直到给出重复值以在唯一字段中更新。我试着这样做:

try{
    if(Employe_info::where('id',$id_to_update)->update($to_update)){
        return redirect()->route('show.employe')->with('success_update', 'Informations were updated successfully.');
    }

}catch(\Illuminate\Database\QueryException $e){
    $errorCode = $e->errorInfo[1];
    if($errorCode == 1062){
        return redirect()->route('edit.user')->with('user_exists', 'Email or ID already exists');
    }
}

如果给出了唯一字段的重复值,我试图捕获QueryException。确切地说,此代码适用于我的create方法。但不适用于我的更新方法,因为它显示相同的错误。 我得到了:

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message

当我试图捕获异常时,这是错误。

这是错误的位置:

C:\xampp\htdocs\laravel_project_1\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php
    if ($request->method() == 'OPTIONS') {
        return (new Route('OPTIONS', $request->path(), function () use ($methods) {
            return new Response('', 200, ['Allow' => implode(',', $methods)]);
        }))->bind($request);
    }

    $this->methodNotAllowed($methods);
}

/**
 * Throw a method not allowed HTTP exception.
 *
 * @param  array  $others
 * @return void
 *
 * @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
 */
protected function methodNotAllowed(array $others)
{
    throw new MethodNotAllowedHttpException($others);
}

如何处理此异常?

1 个答案:

答案 0 :(得分:0)

where()->get()查询构建器方法在找到结果而不是单个实例时返回Collection。如果您已经拥有employee_id,只需使用find()

更改

Employe_info::where('id',$id_to_update)

Employe_info::find($id_to_update)

或者更好的是,在控制器中使用路由模型绑定。

// routes/web.php
Route::patch('/employe_infos/{employe_info}', 'Employe_infoController@update');

// Employe_infoController.php
public function update(Request $request, Employe_info $employe_info)
{
    $attributes = $request->validate([
        // validation rules here
    ]);

    $employe_info->update($attributes);

    return redirect()->route('show.employe')
        ->with('success_update', 'Informations were updated successfully.');
}