如何在 Laravel 8 的請求類中訪問模型實例?

網易

在我的 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();

是否有更簡單的解決方案來訪問類中的當前Post模型Request

羅里

FormRequests 的文檔表明該authorize()方法支持類型提示

如果您正在使用路由模型綁定,則只需在帖子中輸入提示:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章