【发布时间】:2022-01-01 04:48:23
【问题描述】:
在我的 Laravel 项目中,我想通过 Request 像这样授权用户:
<?php
namespace Domain\Contents\Http\Requests\Blog;
use Domain\Contents\Models\Blog\Post;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Gate;
class ReadPostRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
if (request('id') === null) {
abort(403);
}
$post = Post::whereId(request('id'))->first();
return Gate::allows('view-post', $this->user(), $post);
}
// ...
}
但我认为我的这部分代码有点乱:
if (request('id') === null) {
abort(403);
}
$post = Post::whereId(request('id'))->first();
有没有更简单的解决方案可以访问Request 类中的当前Post 模型?
【问题讨论】:
-
您的代码看起来很混乱。如果它不为空,则返回 403,那么如果您知道 ID 为空,为什么还要在后面加上
whereId行? -
如果您没有访问帖子的权限,那么您无权查看哪些帖子 ID 存在,哪些不存在。因此,如果您尝试访问不存在的帖子 404 不是一个好的答案,因为这意味着某些东西不存在。但正确的答案是“不关你的事”。但是如果你想获得一个现有的帖子,那么我有一个决定授权的政策。
-
但你总是返回 403,除非 ID 为空。因此,当您到达
whereId行时,您已经知道 ID 为空,它永远不会获得 post 对象。 -
哦,你是对的 :) 我已经在我的代码中修复了它,但在这个例子中没有。我现在修好了。
标签: laravel authorization laravel-8 laravel-authorization laravel-request