如何确保用户只能使用 Laravel 删除自己的记录
How to make sure a user can only delete his own records using Laravel
如何确保用户只能删除自己的记录。
下面是我如何删除 post 和以下内容 url。
现在用户也可以在此处传递任何 post id,然后无论 post 不属于用户,该 id 的记录都将被删除。
我如何使用 Laravel
来解决这个问题
最好的方法是use policies为了这个目的
Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a Post
model and a corresponding PostPolicy
to authorize user actions such as creating
or updating
posts.
如果出于某种原因您不想使用政策,您可以手动检查用户:
if (auth()->check && auth()->user()->id === $post->user_id) {
// Delete post.
}
如何确保用户只能删除自己的记录。
下面是我如何删除 post 和以下内容 url。
现在用户也可以在此处传递任何 post id,然后无论 post 不属于用户,该 id 的记录都将被删除。 我如何使用 Laravel
来解决这个问题最好的方法是use policies为了这个目的
Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a
Post
model and a correspondingPostPolicy
to authorize user actions such ascreating
orupdating
posts.
如果出于某种原因您不想使用政策,您可以手动检查用户:
if (auth()->check && auth()->user()->id === $post->user_id) {
// Delete post.
}