【问题标题】:How to access model instance in a Request class in Laravel 8?如何在 Laravel 8 的 Request 类中访问模型实例?
【发布时间】: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


【解决方案1】:

FormRequests 的文档建议 authorize() 方法 supports type hinting

如果您使用的是路由模型绑定,则只需键入提示帖子:

public function authorize(Post $post)
{
    return Gate::allows('view-post', $this->user(), $post);
}

【讨论】:

    【解决方案2】:

    替代解决方案是您可以直接访问与模型绑定一起使用的模型。

    return Gate::allows('view-post', $this->user(), $this->post);
    

    为了便于使用,您可以在 cmets 中输入提示。

    /**
     * @property \App\Models\Post $post
     */
    

    【讨论】:

      猜你喜欢
      • 2020-09-14
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 2021-06-03
      • 2011-05-06
      • 1970-01-01
      • 2013-07-09
      相关资源
      最近更新 更多