gpt4 book ai didi

php - 如何防止模型注入(inject)绑定(bind)错误的 uuid?

转载 作者:行者123 更新时间:2023-11-29 13:08:35 25 4
gpt4 key购买 nike

使用 Laravel 6,我在 Controller 中注入(inject)一个模型,如下所示:

public function edit(School $school)
{
return view('/school/form', ['school' => $school]);
}

当我输入这样的 url 时,一切正常:

http://localhost:8000/schools/3d537a0f-4c74-4fae-99af-6f1b2c4b34c8/edit

但是如果我尝试另一个像这样的 url(uuid 错误):

http://localhost:8000/schools/3d537a0f-4c74-4fae-99af-6f/edit

然后我有这个 PostgreSQL 错误:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalidinput syntax for type uuid: "3d537a0f-4c74-4fae-99af-6f1b2c4b34c"(SQL: select * from "schools" where "id" =3d537a0f-4c74-4fae-99af-6f1b2c4b34c limit 1)

这是否意味着我必须先检查 uuid?有什么优雅的方法可以防止这种情况并自动重定向到 404 页面吗?

最佳答案

在你的路由定义中,你可以对参数使用约束来避免匹配:

Route::get('school/{school}/edit', 'SchoolController@edit')
->where('school', '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$');

这将导致 404,因为路由不匹配无效的 UUID。可以找到有关此主题的更多信息 in the documentation .还有一个解释如何定义全局约束以避免为每条路线重复它。


对于资源路由,解决方案略有不同。您需要在 RouteServiceProviderboot() 方法中定义全局约束:

Route::pattern('school', '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$');

如果您的资源调用方式与您的路由参数不同,您需要在定义路由资源时自定义参数名称:

Route::resource('university', 'UniversityController', [
'parameters' => ['university' => 'school']
]);

注意:这只是为了说明,我怀疑你需要它......

关于php - 如何防止模型注入(inject)绑定(bind)错误的 uuid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57901103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com