You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8中如何在Request类内访问对应模型实例

Laravel FormRequest 中直接获取Post模型实例的简化方案

最推荐的方案是使用Laravel 隐式路由模型绑定,这是框架原生支持的能力,完全可以省略你写的冗余判断、查询逻辑:

  • 第一步:调整路由定义,将路由参数命名为和模型对应的名称,示例代码:
// 路由文件中定义
Route::get('/blog/posts/{post}', [\Domain\Contents\Http\Controllers\Blog\PostController::class, 'show'])
    ->middleware('auth');

这里的{post}就是路由参数名,和你的Post模型对应,Laravel会自动根据参数值查询对应Post实例,找不到直接返回404,不需要你手动判断参数是否存在、手动查询。

  • 第二步:直接在ReadPostRequest的authorize方法中获取绑定好的Post实例,优化后的代码如下:
<?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()
    {
        // 直接通过route方法获取已经绑定好的Post模型实例
        return Gate::allows('view-post', $this->user(), $this->route('post'));
    }

    // ...
}

可选补充方案

如果你的Post的id是放在请求参数(Query参数/请求Body)中,不是路由参数,可以通过prepareForValidation方法提前查询模型,后续多处都可以直接复用:

<?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
{
    // 提前查询Post模型存入请求属性
    protected function prepareForValidation()
    {
        $this->merge([
            'post' => Post::findOrFail($this->input('id'))
        ]);
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Gate::allows('view-post', $this->user(), $this->input('post'));
    }

    // ...
}

这里用findOrFail方法,id不存在或者对应Post找不到时会自动抛出404异常,不需要手动写判空、abort逻辑。

内容的提问来源于stack exchange,提问作者netdjw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 01:36:00