gpt4 book ai didi

mysql - Laravel Eloquent 如何限制登录用户的访问权限

转载 作者:太空宇宙 更新时间:2023-11-03 12:18:20 25 4
gpt4 key购买 nike

我有一个小应用程序,用户可以在其中创建分配给他们的东西。

有多个用户,但所有的东西都在同一个表中。我通过检索具有该用户 ID 的所有事物来显示属于该用户的事物,但没有什么可以阻止用户通过在 URL 中手动键入事物的 ID 来查看其他用户的事物。

此外,当用户想要创建新事物时,我将验证规则设置为唯一,但显然如果其他人有同名事物,那将无法工作。

在我的 Eloquent 模型中是否有一种方法可以指定所有交互只允许属于已登录用户的事物?

这意味着当用户尝试访问/thing/edit 并且他不拥有那个东西时,他会收到一条错误消息。

最佳答案

执行此操作的最佳方法是检查“事物”是否属于“事物” Controller 中的用户。

例如,在 Controller 中,您可以这样做:

// Assumes that the controller receives $thing_id from the route.
$thing = Things::find($thing_id); // Or how ever you retrieve the requested thing.

// Assumes that you have a 'user_id' column in your "things" table.
if( $thing->user_id == Auth::user()->id ) {
//Thing belongs to the user, display thing.
} else {
// Thing does not belong to the current user, display error.
}

同样可以使用关系表来完成。

// Get the thing based on current user, and a thing id 
// from somewhere, possibly passed through route.
// This assumes that the controller receives $thing_id from the route.
$thing = Users::find(Auth::user()->id)->things()->where('id', '=', $thing_id)->first();

if( $thing ) {
// Display Thing
} else {
// Display access denied error.
}

第三个选项:

// Same as the second option, but with firstOrFail().
$thing = Users::find(Auth::user()->id)->things()->where('id', '=', $thing_id)->firstOrFail();

// No if statement is needed, as the app will throw a 404 error
// (or exception if errors are on)

如果我错了请指正我,我自己也是laravel的新手。但我相信这就是你想要做的。如果没有看到你的“事物”、“事物”路由或“事物” Controller 的代码,或者你的“事物”模型是如何使用 Eloquent (如果你使用 Eloquent )设置的,我帮不上什么忙。

关于mysql - Laravel Eloquent 如何限制登录用户的访问权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21149956/

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